### Render with 'sharp' Engine Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Instructions and example for using the 'sharp' render engine, recommended for PNG output. Includes installation instructions for the 'sharp' package. ```APIDOC #### render: `sharp` It's recommended to use `sharp` for rendering to PNG. `sharp` is an optional dependency, so you need to install it manually, before using it: ```bash # yarn add sharp # pnpm install sharp npm install sharp ``` Example: ```typescript const image = await page.render({ scale: 3, render: 'sharp', }); console.log(image.data); // PNG image data as a buffer ``` ``` -------------------------------- ### Start Local Development Server Source: https://github.com/hyzyla/pdfium/blob/main/docs/README.md Starts a local development server and opens the website in a browser. Changes are reflected live. ```bash $ yarn start ``` -------------------------------- ### Install @hyzyla/pdfium Source: https://github.com/hyzyla/pdfium/blob/main/README.md Install the package using npm, yarn, or pnpm. ```sh npm install @hyzyla/pdfium ``` -------------------------------- ### Install @hyzyla/pdfium Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/01-intro.md Install the @hyzyla/pdfium package using your preferred package manager. ```bash npm install @hyzyla/pdfium ``` ```bash # yarn add @hyzyla/pdfium # pnpm install @hyzyla/pdfium ``` -------------------------------- ### Install Sharp Dependency Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Install the 'sharp' package, which is an optional dependency recommended for rendering PDFs to PNG format. ```bash # yarn add sharp # pnpm install sharp npm install sharp ``` -------------------------------- ### Install Dependencies Source: https://github.com/hyzyla/pdfium/blob/main/docs/README.md Installs project dependencies using Yarn. ```bash $ yarn ``` -------------------------------- ### Initialize PDFiumLibrary in Browser (CDN) Source: https://context7.com/hyzyla/pdfium/llms.txt Initialize the PDFium library in a browser environment using a CDN. This is a quick setup but not recommended for production. ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium/browser/cdn'; const library = await PDFiumLibrary.init(); ``` -------------------------------- ### Quick Browser Setup: Load .wasm from CDN Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/02-init-library.md For quick testing in the browser, load the .wasm file from a CDN. This is not recommended for production due to potential overhead and security risks. ```typescript import { PDFiumLibrary } from "@hyzyla/pdfium/browser/cdn"; const library = await PDFiumLibrary.init(); ``` -------------------------------- ### Quick Browser Setup: Load .wasm from Base64 Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/02-init-library.md For quick testing, load the .wasm file from a base64-encoded string. This approach is not recommended for production as it increases bundle size. ```typescript import { PDFiumLibrary } from "@hyzyla/pdfium/browser/base64"; const library = await PDFiumLibrary.init(); ``` -------------------------------- ### Render with Custom Function Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Guide on providing a custom render function to the `render` method, allowing for flexible image format conversion. ```APIDOC #### render: custom render function You can also pass a custom render function as the `render` option. It should be a function that accepts a `RenderPageOptions` object and returns a `Promise` object. You can use it to render to any image format: ```typescript import sharp from 'sharp'; import { type PDFiumPageRenderOptions } from '@hyzyla/pdfium'; const image = await page.render({ scale: 3, render: async (options: PDFiumPageRenderOptions): Promise => { return await sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4, }, }) .png() .toBuffer(); }, }); ``` ``` -------------------------------- ### Initialize PDFiumLibrary in Browser with Rollup Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/02-init-library.md In the browser, provide the URL to the .wasm binary or an ArrayBuffer. This example uses Rollup to import the .wasm file as an asset URL. ```typescript import { PDFiumLibrary } from "@hyzyla/pdfium/browser/cdn"; import wasmUrl from "@hyzyla/pdfium/pdfium.wasm?url"; // URL to the .wasm file const library = await PDFiumLibrary.init({ wasmUrl: wasmUrl, }); ``` -------------------------------- ### Get and Render PDF Page Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Explains how to retrieve a specific page from a document using `getPage` or iterate through pages using `pages`, and then render the page to an image. ```APIDOC ## Render PDF Page Before rendering a PDF page, you need to get it from the document. You can do this by calling `getPage` method of the document instance. First argument is the page number (starting from 0). ```typescript const page = document.getPage(0); ``` or you can iterate over the pages using `pages` method of the document instance: ```typescript for (const page of document.pages()) { // ... do something with the page } ``` Then you can render the page to an image by calling `render` method of the page instance. It accepts an optional `PDFiumPageRenderParams` object with the following properties: - `scale` - scale factor for the image (default is 1, which means 72 DPI, 3 almost always is enough for good quality) - `render` - render engine to use, can be either `sharp`, `bitmap` (default is `bitmap`) or custom render function. If you need to render to PNG, it's recommended to use `sharp` render function. - `colorSpace` - color space to render to: `'BGRA'` (default, full color) or `'Gray'` (grayscale, useful for OCR) - `renderFormFields` - whether to render interactive form fields (default is `false`). Form fields are interactive elements like text boxes, checkboxes, dropdown menus, and signature fields that users can fill out in PDF documents (like tax forms, applications, or contracts). ```typescript const image = await page.render({ scale: 3, render: 'sharp', }); ``` To render with form fields visible: ```typescript const image = await page.render({ scale: 3, render: 'sharp', renderFormFields: true, }); ``` Result is an object with the following properties: - `data` - image data as a buffer - `width` - image width in points (after scaling) - `height` - image height in points (after scaling) - `originalWidth` - original page width in points (before scaling) - `originalHeight` - original page height in points (before scaling) :::info DPI is dots per inch, it's a measure of image resolution and commonly used for printing Points are a typographic unit of measure, 1 point is equal to 1/72 of an inch ::: ``` -------------------------------- ### Render PDF Page with Sharp Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Render a PDF page to an image using the 'sharp' engine for PNG output. Install 'sharp' separately. Adjust 'scale' for resolution; a scale of 3 is often sufficient. ```typescript const image = await page.render({ scale: 3, render: 'sharp', }); ``` -------------------------------- ### Get PDF Page Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Retrieve a specific page from a loaded PDF document using its index. ```typescript const page = document.getPage(0); ``` -------------------------------- ### Get total page count of a PDF document Source: https://context7.com/hyzyla/pdfium/llms.txt Retrieve the total number of pages in a loaded PDF document. ```typescript const count = document.getPageCount(); console.log(`This PDF has ${count} pages`); // e.g. "This PDF has 4 pages" ``` -------------------------------- ### Reduce Image Size with Custom Render Function Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/04-extract-images-from-page.md Extracts an image from a PDF page and applies compression using `sharp` to reduce its file size. This example demonstrates using a custom render function to convert the image to JPEG format with a specified quality. ```typescript import sharp from 'sharp'; import { PDFiumPageRenderOptions } from '@hyzyla/pdfium'; const document = await library.loadDocument(buff); const page = document.getPage(0); const object = page.getObject(0); const image = await object.render({ render: async (options: PDFiumPageRenderOptions): Promise => { return await sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4, }, }) .jpeg({ quality: 80 }) // Use JPEG format with 80% quality .toBuffer(); }, }); ``` -------------------------------- ### Get a specific page from a PDF document Source: https://context7.com/hyzyla/pdfium/llms.txt Load and retrieve a single PDF page by its zero-based index. The `page.number` property returns the index. ```typescript // Get the first page (index 0) const firstPage = document.getPage(0); console.log(firstPage.number); // 0 // Get the last page const lastPage = document.getPage(document.getPageCount() - 1); ``` -------------------------------- ### Render PDF Page to PNG Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Renders a PDF page to a PNG image using a custom render function. Ensure the 'sharp' library is installed for bitmap conversion. The render function takes page dimensions and raw bitmap data, returning a PNG buffer. ```typescript import { PDFiumLibrary } from "@hyzyla/pdfium"; import { promises as fs } from 'fs'; import sharp from 'sharp'; /** * For this and the following examples, we will use "sharp" library to convert * the raw bitmap data to PNG images. You can use any other library or write * your own function to convert the raw bitmap data to PNG images. */ async function renderFunction(options: PDFiumPageRenderOptions) { return await sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4, }, }) .png() .toBuffer(); } async main() { const buff = await fs.readFile('test2.pdf'); // Initialize the library, you can do this once for the whole application // and reuse the library instance. const library = await PDFiumLibrary.init(); // Load the document from the buffer // You can also pass "password" as the second argument if the document is encrypted. const document = await library.loadDocument(buff); // Iterate over the pages, render them to PNG images and // save to the output folder for (const page of document.pages()) { console.log(`${page.number} - rendering...`); // Render PDF page to PNG image const image = await page.render({ scale: 3, // 3x scale (72 DPI is the default) render: renderFunction, }); // Save the PNG image to the output folder await fs.writeFile(`output/${page.number}.png`, Buffer.from(image.data)); } // Do not forget to destroy the document and the library // when you are done. document.destroy(); library.destroy(); } main(); ``` -------------------------------- ### Freeing WASM Memory with PDFiumDocument.destroy() and PDFiumLibrary.destroy() Source: https://context7.com/hyzyla/pdfium/llms.txt Always call document.destroy() after you are done with a document, and library.destroy() when the library is no longer needed to prevent memory leaks. This example demonstrates proper cleanup within a try...finally block. ```typescript const library = await PDFiumLibrary.init(); const document = await library.loadDocument(buff); try { for (const page of document.pages()) { const image = await page.render({ scale: 2, render: 'sharp' }); await fs.writeFile(`page_${page.number}.png`, image.data); } } finally { // Always free resources even if rendering throws document.destroy(); library.destroy(); } ``` -------------------------------- ### Get a PDFiumPage object by index Source: https://context7.com/hyzyla/pdfium/llms.txt Retrieves a typed PDFiumObject at a specific index on the page. Use `obj.type` to narrow down to subtypes like `PDFiumImageObject` for further processing. ```typescript const page = document.getPage(0); const obj = page.getObject(0); console.log(obj.type); // "text" | "path" | "image" | "shading" | "form" if (obj.type === 'image') { // obj is now typed as PDFiumImageObject const rendered = await obj.render({ render: 'sharp' }); console.log(rendered.width, rendered.height); } ``` -------------------------------- ### Get raw compressed image data from PDFiumImageObject Source: https://context7.com/hyzyla/pdfium/llms.txt Retrieves the raw, potentially compressed, image data as stored in the PDF stream. Also returns width, height, and an array of filters (e.g., `["DCTDecode"]` for JPEG). Useful for saving original compressed bytes without re-encoding. ```typescript const document = await library.loadDocument(buff); for (const page of document.pages()) { for (const obj of page.objects()) { if (obj.type === 'image') { const { data, width, height, filters } = await obj.getImageDataRaw(); console.log({ width, height, filters, bytes: data.length }); // Example output: // { width: 313, height: 234, filters: ['DCTDecode'], bytes: 1523 } // { width: 400, height: 400, filters: ['FlateDecode'], bytes: 57828 } // { width: 640, height: 480, filters: ['FlateDecode'], bytes: 680515 } // For DCTDecode images, data is a raw JPEG buffer you can save directly: if (filters.includes('DCTDecode')) { await fs.writeFile('image.jpg', data); } } } } document.destroy(); ``` -------------------------------- ### Get original PDF page dimensions Source: https://context7.com/hyzyla/pdfium/llms.txt Retrieves the native width and height of a PDF page in PDF points (1 pt = 1/72 inch). This is the size before any scaling is applied, useful for calculating pixel dimensions at a target DPI. ```typescript const document = await library.loadDocument(buff); const page = document.getPage(0); const { originalWidth, originalHeight } = page.getOriginalSize(); console.log(`${originalWidth} x ${originalHeight} pts`); // A4 page: "595 x 841 pts" (595 pt ≈ 210 mm, 841 pt ≈ 297 mm at 72 DPI) // Compute a target DPI manually: const targetDPI = 300; const scale = targetDPI / 72; const pixelWidth = Math.round(originalWidth * scale); // 2480 const pixelHeight = Math.round(originalHeight * scale); // 3508 const image = await page.render({ scale, render: 'sharp' }); console.log(image.width, image.height); // 2480 x 3508 document.destroy(); ``` -------------------------------- ### Deploy Website (SSH) Source: https://github.com/hyzyla/pdfium/blob/main/docs/README.md Builds the website and deploys it using SSH. Assumes SSH is configured for deployment. ```bash $ USE_SSH=true yarn deploy ``` -------------------------------- ### PDFiumLibrary.init() Source: https://context7.com/hyzyla/pdfium/llms.txt Initializes a singleton library instance backed by the PDFium WebAssembly module. This instance should be reused and destroyed when no longer needed. ```APIDOC ## PDFiumLibrary.init() ### Description Creates and initializes a singleton library instance backed by the PDFium WebAssembly module. In Node.js, the `.wasm` binary is resolved automatically. In the browser, you must supply `wasmUrl` or `wasmBinary`. The returned instance should be reused for the lifetime of the application and destroyed with `library.destroy()` when no longer needed. ### Method `static async init(options?: { wasmUrl?: string; wasmBinary?: ArrayBuffer }): Promise ### Parameters #### Options - **wasmUrl** (string) - Optional - URL to the bundled `.wasm` file (recommended for browser production). - **wasmBinary** (ArrayBuffer) - Optional - An ArrayBuffer of the `.wasm` binary directly. ### Request Example ```typescript // Node.js import { PDFiumLibrary } from '@hyzyla/pdfium'; const library = await PDFiumLibrary.init(); // Browser (using wasmUrl) import { PDFiumLibrary } from '@hyzyla/pdfium/browser/cdn'; import wasmUrl from '@hyzyla/pdfium/pdfium.wasm?url'; const library = await PDFiumLibrary.init({ wasmUrl }); // Browser (using embedded base64) import { PDFiumLibrary } from '@hyzyla/pdfium/browser/base64'; const library = await PDFiumLibrary.init(); // Browser (using wasmBinary) const wasmBinary = await fetch(wasmUrl).then(res => res.arrayBuffer()); const library = await PDFiumLibrary.init({ wasmBinary }); // Always destroy when done library.destroy(); ``` ``` -------------------------------- ### Initialize PDFiumLibrary Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/02-init-library.md Create a PDFiumLibrary instance. This can be done once and reused throughout the application's lifetime. Remember to call `destroy()` when done. ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium'; const library = await PDFiumLibrary.init(); // ... do something with the library library.destroy(); ``` -------------------------------- ### Initialize PDFiumLibrary in Browser (Base64) Source: https://context7.com/hyzyla/pdfium/llms.txt Initialize the PDFium library in a browser environment using an embedded base64 encoded WASM binary. This results in a larger bundle size. ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium/browser/base64'; const library = await PDFiumLibrary.init(); ``` -------------------------------- ### Import PDFium Library Source: https://github.com/hyzyla/pdfium/blob/main/demo/plain/main.html Demonstrates how to import the PDFium library using CDN. Note that the provided import path for 'path' and 'fs' is a placeholder and may require adjustment for actual use. ```javascript { "imports": { "@hyzyla/pdfium": "https://cdn.jsdelivr.net/npm/@hyzyla/pdfium@2.0.1/dist/index.esm.js", "path": {}, "fs": {} } } // todo: fix this, it doesn't work import {PDFiumLibrary} from "@hyzyla/pdfium"; ``` -------------------------------- ### Build Static Website Source: https://github.com/hyzyla/pdfium/blob/main/docs/README.md Generates static website content into the 'build' directory for hosting. ```bash $ yarn build ``` -------------------------------- ### Initialize PDFiumLibrary in Node.js Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/02-init-library.md For Node.js, the .wasm file is automatically loaded from `node_modules`. No additional configuration is needed. ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium'; const library = await PDFiumLibrary.init(); ``` -------------------------------- ### Deploy Website (No SSH) Source: https://github.com/hyzyla/pdfium/blob/main/docs/README.md Builds the website and deploys it without using SSH. Requires specifying the GitHub username. ```bash $ GIT_USER= yarn deploy ``` -------------------------------- ### Initialize PDFiumLibrary with WASM Binary Source: https://context7.com/hyzyla/pdfium/llms.txt Advanced initialization in Node.js or browser by supplying an ArrayBuffer of the .wasm binary directly. ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium'; import { promises as fs } from 'fs'; // Advanced — supply an ArrayBuffer of the .wasm binary directly const wasmBinary = await fs.readFile('./node_modules/@hyzyla/pdfium/dist/pdfium.wasm'); const library = await PDFiumLibrary.init({ wasmBinary }); ``` -------------------------------- ### Initialize PDFiumLibrary in Node.js Source: https://context7.com/hyzyla/pdfium/llms.txt Initialize the PDFium library in a Node.js environment. The WASM binary is resolved automatically. ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium'; import { promises as fs } from 'fs'; // Node.js — no extra options needed const library = await PDFiumLibrary.init(); ``` -------------------------------- ### Render by Width and Height Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Explains how to specify exact `width` and `height` for rendering, overriding the `scale` option, and notes that aspect ratio is not preserved by default. ```APIDOC #### render: `width` and `height`, instead of `scale` You can use the `width` and `height` options instead of scale to specify the exact image size in points that you want to render. In this case, the aspect ratio will not be preserved, and the image will be stretched to the specified size. If you want to preserve the aspect ratio, you can manually calculate the width and height based on the original image size and the desired scale. ```typescript const image = await page.render({ width: 800, height: 600, render: 'sharp', }); ``` ``` -------------------------------- ### Initialize PDFiumLibrary in Browser (WASM URL) Source: https://context7.com/hyzyla/pdfium/llms.txt Initialize the PDFium library in a browser environment by providing the URL to the bundled .wasm file. This is the recommended approach for production. ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium/browser/cdn'; import wasmUrl from '@hyzyla/pdfium/pdfium.wasm?url'; const library = await PDFiumLibrary.init({ wasmUrl }); ``` -------------------------------- ### Load PDF Document Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Demonstrates how to load a PDF document from a buffer and the importance of destroying the document instance after use. ```APIDOC ## Load PDF Document ```typescript const document = await library.loadDocument(buff); // ... do something with the document document.destroy(); ``` ``` -------------------------------- ### Render with 'bitmap' Engine Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Details on using the default 'bitmap' render engine, which outputs raw pixel data and does not require additional dependencies. ```APIDOC #### render: `bitmap` `bitmap` is the default render engine. It renders PDF page to a bitmap image, which is a buffer of RGBA pixels (4 channels) by default, or a single-channel grayscale buffer if `colorSpace: 'Gray'` is used. You can use it to render to any image format, but you need to convert the bitmap to the desired format yourself. It's default render engine, because it doesn't require any additional dependencies. Example: ```typescript const image = await page.render({ scale: 3, render: 'bitmap', }); console.log(image.data); // Bitmap image data as a buffer ``` ``` -------------------------------- ### PDFiumDocument.initializeFormFields() Source: https://context7.com/hyzyla/pdfium/llms.txt Initializes the PDFium form fill environment for the document. This must be called before form widgets will appear in rendered output. It is idempotent. ```APIDOC ## `PDFiumDocument.initializeFormFields()` — Enable interactive form rendering ### Description Initializes the PDFium form fill environment for the document. This must be called (or enabled via `renderFormFields: true` on `page.render()`) before form widgets — text inputs, checkboxes, dropdowns, and signatures — will appear in rendered output. Idempotent: calling it multiple times returns the same handle. ### Usage ```typescript const document = await library.loadDocument(buff); // Called automatically when renderFormFields: true is passed to page.render() // Can also be invoked manually: const formHandle = document.initializeFormFields(); console.log('Form environment handle:', formHandle); // non-zero number on success document.destroy(); ``` ``` -------------------------------- ### Render PDF Page by Width and Height Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Render a PDF page to a specific width and height using the 'sharp' engine. Note that this may stretch the image if the aspect ratio is not maintained. ```typescript const image = await page.render({ width: 800, height: 600, render: 'sharp', }); ``` -------------------------------- ### Load a plain PDF document Source: https://context7.com/hyzyla/pdfium/llms.txt Load a plain PDF document from a Uint8Array buffer into WASM memory. Ensure the library is initialized first. ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium'; import { promises as fs } from 'fs'; const library = await PDFiumLibrary.init(); const buff = await fs.readFile('document.pdf'); // Plain document const document = await library.loadDocument(buff); ``` -------------------------------- ### Initialize PDFium Form Fields Source: https://context7.com/hyzyla/pdfium/llms.txt Call this to enable interactive form rendering. It must be called before form widgets appear in rendered output. It is idempotent. ```typescript const document = await library.loadDocument(buff); // Called automatically when renderFormFields: true is passed to page.render() // Can also be invoked manually: const formHandle = document.initializeFormFields(); console.log('Form environment handle:', formHandle); // non-zero number on success document.destroy(); ``` -------------------------------- ### Render PDF Page with Bitmap Engine Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Render a PDF page using the default 'bitmap' engine. This produces a raw pixel buffer and requires no additional dependencies. ```typescript const image = await page.render({ scale: 3, render: 'bitmap', }); console.log(image.data); // Bitmap image data as a buffer ``` -------------------------------- ### Render PDF Pages to PNG Source: https://github.com/hyzyla/pdfium/blob/main/README.md Loads a PDF, iterates through pages, renders each to PNG using a custom render function (sharp), and saves the output. Ensure the PDFium library is initialized once and destroyed when done. The render function converts raw bitmap data to PNG. ```ts import { PDFiumLibrary } from "@hyzyla/pdfium"; import { promises as fs } from 'fs'; import sharp from 'sharp'; /** * For this and the following examples, we will use "sharp" library to convert * the raw bitmap data to PNG images. You can use any other library or write * your own function to convert the raw bitmap data to PNG images. */ async function renderFunction(options: PDFiumPageRenderOptions) { return await sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4, }, }) .png() .toBuffer(); } async function main() { const buff = await fs.readFile('test2.pdf'); // Initialize the library, you can do this once for the whole application // and reuse the library instance. const library = await PDFiumLibrary.init(); // Load the document from the buffer // You can also pass "password" as the second argument if the document is encrypted. const document = await library.loadDocument(buff); // Iterate over the pages, render them to PNG images and // save to the output folder for (const page of document.pages()) { console.log(`${page.number} - rendering...`); // Render PDF page to PNG image const image = await page.render({ scale: 3, // 3x scale (72 DPI is the default) render: renderFunction, // sharp function to convert raw bitmap data to PNG }); // Save the PNG image to the output folder await fs.writeFile(`output/${page.number}.png`, Buffer.from(image.data)); } // Do not forget to destroy the document and the library // when you are done. document.destroy(); library.destroy(); } main(); ``` -------------------------------- ### PDFiumLibrary.loadDocument() Source: https://context7.com/hyzyla/pdfium/llms.txt Loads a PDF document from a Uint8Array buffer into WASM memory. Supports password-protected documents and throws descriptive errors for invalid files. ```APIDOC ## PDFiumLibrary.loadDocument() ### Description Reads a PDF from a `Uint8Array` buffer into WASM memory and returns a `PDFiumDocument` handle. An optional password string is required for encrypted documents. Throws descriptive errors for invalid, corrupted, password-protected, or unsupported files. Call `document.destroy()` when done. ### Method `async loadDocument(buffer: Uint8Array, password?: string): Promise ### Parameters #### Path Parameters - **buffer** (Uint8Array) - Required - The PDF file content as a byte array. - **password** (string) - Optional - The password for encrypted documents. ### Request Example ```typescript import { PDFiumLibrary } from '@hyzyla/pdfium'; import { promises as fs } from 'fs'; const library = await PDFiumLibrary.init(); const buff = await fs.readFile('document.pdf'); // Plain document const document = await library.loadDocument(buff); // Password-protected document const buffEncrypted = await fs.readFile('secure.pdf'); try { const docEncrypted = await library.loadDocument(new Uint8Array(buffEncrypted), '12345678'); console.log('Pages:', docEncrypted.getPageCount()); docEncrypted.destroy(); } catch (err) { console.error(err.message); } document.destroy(); library.destroy(); ``` ### Response #### Success Response (200) - **PDFiumDocument** - A handle to the loaded PDF document. #### Error Response - **Error** - Throws descriptive errors for invalid, corrupted, password-protected, or unsupported files. ``` -------------------------------- ### PDFiumPage.render() Source: https://context7.com/hyzyla/pdfium/llms.txt Renders the PDF page to an image buffer. Accepts an optional PDFiumPageRenderParams object and returns a PDFiumPageRender object. ```APIDOC ## `PDFiumPage.render()` — Render a page to an image ### Description Renders the PDF page to an image buffer. Accepts an optional `PDFiumPageRenderParams` object. Returns a `PDFiumPageRender` object containing `data` (the image buffer), `width`, `height` (post-scaling), `originalWidth`, and `originalHeight` (in PDF points at 72 DPI). ### Render params: | Option | Type | Default | Description | |---|---|---|---| | `scale` | `number` | `1` | Multiplier over 72 DPI base resolution | | `width` | `number` | — | Explicit output width in pixels (overrides scale) | | `height` | `number` | — | Explicit output height in pixels (overrides scale) | | `render` | `"bitmap"` | `"bitmap"` | Output format / render engine | | `colorSpace` | `"BGRA"` | `"BGRA"` | Pixel color space | | `renderFormFields` | `boolean` | `false` | Whether to render interactive form widgets | ### Usage ```typescript import { PDFiumLibrary, type PDFiumPageRenderOptions } from '@hyzyla/pdfium'; import { promises as fs } from 'fs'; import sharp from 'sharp'; const library = await PDFiumLibrary.init(); const buff = await fs.readFile('document.pdf'); const document = await library.loadDocument(buff); // 1. Bitmap render (raw BGRA pixels, no extra dependencies) const bitmap = await document.getPage(0).render({ scale: 2, render: 'bitmap' }); console.log(bitmap.width, bitmap.height); // e.g. 1190 x 1682 at 2x scale console.log(bitmap.data.length); // width * height * 4 bytes // 2. Sharp render — produces a PNG buffer directly const pngResult = await document.getPage(0).render({ scale: 3, render: 'sharp' }); await fs.writeFile('page0.png', pngResult.data); // 3. Custom render function — full control over output format const jpegResult = await document.getPage(0).render({ scale: 2, render: async (options: PDFiumPageRenderOptions): Promise => { return await sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4 }, }).jpeg({ quality: 85 }).toBuffer(); }, }); await fs.writeFile('page0.jpg', jpegResult.data); // 4. Exact pixel dimensions (aspect ratio NOT preserved) const sized = await document.getPage(0).render({ width: 800, height: 600, render: 'sharp' }); console.log(sized.width, sized.height); // 800 x 600 // 5. Grayscale render (1 channel, useful for OCR) const gray = await document.getPage(0).render({ scale: 2, colorSpace: 'Gray', render: async (options) => sharp(options.data, { raw: { width: options.width, height: options.height, channels: 1 } }) .png().toBuffer(), }); // 6. Render with form fields (text boxes, checkboxes, signatures) const withForms = await document.getPage(0).render({ scale: 3, render: 'sharp', renderFormFields: true, }); await fs.writeFile('page0_with_forms.png', withForms.data); document.destroy(); library.destroy(); ``` ``` -------------------------------- ### Load PDF Document Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Load a PDF document from a buffer. Ensure to destroy the document when done to free resources. ```typescript const document = await library.loadDocument(buff); // ... do something with the document document.destroy(); ``` -------------------------------- ### Extract Images from PDF Page using Sharp Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/04-extract-images-from-page.md Iterates through all objects on each page of a PDF document, identifies image objects, and renders them to PNG format using the `sharp` rendering engine. Saves each extracted image to the output folder. ```typescript const document = await library.loadDocument(buff); let index = 0; // Iterate over pages in the document for (const page of document.pages()) { // Iterate over objects in the page for (const object of page.objects()) { // We are interested only in image objects if (object.type === "image") { // Render the image using the sharp rendering engine const { data: image } = await object.render({ render: renderFunction, }); // Save the PNG image to the output folder await fs.writeFile(`output/${index}.png`, Buffer.from(image.data)); index++; } } } ``` -------------------------------- ### PDFiumDocument.getPage() Source: https://context7.com/hyzyla/pdfium/llms.txt Loads and returns a specific page from the document by its zero-based index. ```APIDOC ## PDFiumDocument.getPage() ### Description Loads a single page by its zero-based index and returns a `PDFiumPage` instance. Use `page.number` to read back the zero-based index. ### Method `getPage(index: number): PDFiumPage ### Parameters #### Path Parameters - **index** (number) - Required - The zero-based index of the page to retrieve. ### Request Example ```typescript // Get the first page (index 0) const firstPage = document.getPage(0); console.log(firstPage.number); // 0 // Get the last page const lastPage = document.getPage(document.getPageCount() - 1); ``` ``` -------------------------------- ### Load a password-protected PDF document Source: https://context7.com/hyzyla/pdfium/llms.txt Load a password-protected PDF document by providing the password string. Handles encrypted documents and throws errors for incorrect passwords or invalid files. ```typescript // Password-protected document const buffEncrypted = await fs.readFile('secure.pdf'); try { const docEncrypted = await library.loadDocument(new Uint8Array(buffEncrypted), '12345678'); console.log('Pages:', docEncrypted.getPageCount()); // e.g. 4 docEncrypted.destroy(); } catch (err) { // Possible errors: // "Password required or incorrect password" // "File not in PDF format or corrupted" // "Unsupported security scheme" console.error(err.message); } ``` -------------------------------- ### PDFiumPage.objects() Source: https://context7.com/hyzyla/pdfium/llms.txt Provides a generator to iterate over all `PDFiumObject` instances on a page in their original order. This allows for type-narrowing during iteration, making it easy to process different types of objects. ```APIDOC ## `PDFiumPage.objects()` — Iterate over page objects A generator yielding all `PDFiumObject` instances on the page in order, enabling type-narrowing during iteration. ```typescript const document = await library.loadDocument(buff); const page = document.getPage(0); const typeStat: Record = {}; for (const obj of page.objects()) { typeStat[obj.type] = (typeStat[obj.type] ?? 0) + 1; } console.log(typeStat); // Example: { text: 4, image: 3 } document.destroy(); ``` ``` -------------------------------- ### Count Objects on a PDF Page Source: https://context7.com/hyzyla/pdfium/llms.txt Returns the total number of content objects (text, path, image, shading, form) present on a given page. ```typescript const document = await library.loadDocument(buff); const page = document.getPage(0); const count = page.getObjectCount(); console.log(`Page has ${count} objects`); // e.g. "Page has 182 objects" document.destroy(); ``` -------------------------------- ### Render PDF Page with Custom Function Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Render a PDF page using a custom function. The function receives render options and must return a Promise resolving to a Uint8Array, allowing conversion to any image format. ```typescript import sharp from 'sharp'; import { type PDFiumPageRenderOptions } from '@hyzyla/pdfium'; const image = await page.render({ scale: 3, render: async (options: PDFiumPageRenderOptions): Promise => { return await sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4, }, }) .png() .toBuffer(); }, }); ``` -------------------------------- ### Render PDF Page to Image Source: https://context7.com/hyzyla/pdfium/llms.txt Renders a PDF page to an image buffer. Supports various output formats and options like scaling, explicit dimensions, color space, and form field rendering. ```typescript import { PDFiumLibrary, type PDFiumPageRenderOptions } from '@hyzyla/pdfium'; import { promises as fs } from 'fs'; import sharp from 'sharp'; const library = await PDFiumLibrary.init(); const buff = await fs.readFile('document.pdf'); const document = await library.loadDocument(buff); // 1. Bitmap render (raw BGRA pixels, no extra dependencies) const bitmap = await document.getPage(0).render({ scale: 2, render: 'bitmap' }); console.log(bitmap.width, bitmap.height); // e.g. 1190 x 1682 at 2x scale console.log(bitmap.data.length); // width * height * 4 bytes // 2. Sharp render — produces a PNG buffer directly const pngResult = await document.getPage(0).render({ scale: 3, render: 'sharp' }); await fs.writeFile('page0.png', pngResult.data); // 3. Custom render function — full control over output format const jpegResult = await document.getPage(0).render({ scale: 2, render: async (options: PDFiumPageRenderOptions): Promise => { return await sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4 }, }).jpeg({ quality: 85 }).toBuffer(); }, }); await fs.writeFile('page0.jpg', jpegResult.data); // 4. Exact pixel dimensions (aspect ratio NOT preserved) const sized = await document.getPage(0).render({ width: 800, height: 600, render: 'sharp' }); console.log(sized.width, sized.height); // 800 x 600 // 5. Grayscale render (1 channel, useful for OCR) const gray = await document.getPage(0).render({ scale: 2, colorSpace: 'Gray', render: async (options) => sharp(options.data, { raw: { width: options.width, height: options.height, channels: 1 } }) .png().toBuffer(), }); // 6. Render with form fields (text boxes, checkboxes, signatures) const withForms = await document.getPage(0).render({ scale: 3, render: 'sharp', renderFormFields: true, }); await fs.writeFile('page0_with_forms.png', withForms.data); document.destroy(); library.destroy(); ``` -------------------------------- ### PDFiumDocument.pages() Source: https://context7.com/hyzyla/pdfium/llms.txt Provides a generator to iterate over all pages in the document, yielding each PDFiumPage instance. ```APIDOC ## PDFiumDocument.pages() ### Description A generator that yields each `PDFiumPage` in order, enabling `for...of` iteration without manually managing page indices. ### Method `pages(): IterableIterator ### Request Example ```typescript for (const page of document.pages()) { console.log(`Processing page ${page.number + 1} of ${document.getPageCount()}`); // page is a PDFiumPage instance } ``` ``` -------------------------------- ### Render PDF Page with Form Fields Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Render a PDF page including interactive form fields. Set 'renderFormFields' to true. ```typescript const image = await page.render({ scale: 3, render: 'sharp', renderFormFields: true, }); ``` -------------------------------- ### Iterate Over PDF Pages Source: https://github.com/hyzyla/pdfium/blob/main/docs/docs/03-render-pdf.md Iterate through all pages of a PDF document to process each one. ```typescript for (const page of document.pages()) { // ... do something with the page } ``` -------------------------------- ### PDFiumPage.getObjectCount() Source: https://context7.com/hyzyla/pdfium/llms.txt Returns the total number of content objects (text, path, image, shading, form) on the page. ```APIDOC ## `PDFiumPage.getObjectCount()` — Count page objects ### Description Returns the total number of content objects (text, path, image, shading, form) on the page. ### Usage ```typescript const document = await library.loadDocument(buff); const page = document.getPage(0); const count = page.getObjectCount(); console.log(`Page has ${count} objects`); // e.g. "Page has 182 objects" document.destroy(); ``` ``` -------------------------------- ### Iterate over PDFiumPage objects Source: https://context7.com/hyzyla/pdfium/llms.txt A generator that yields all `PDFiumObject` instances on a page in order. This allows for type-narrowing during iteration, useful for collecting statistics or processing specific object types. ```typescript const document = await library.loadDocument(buff); const page = document.getPage(0); const typeStat: Record = {}; for (const obj of page.objects()) { typeStat[obj.type] = (typeStat[obj.type] ?? 0) + 1; } console.log(typeStat); // Example: { text: 4, image: 3 } document.destroy(); ``` -------------------------------- ### Destroy PDFiumLibrary instance Source: https://context7.com/hyzyla/pdfium/llms.txt Always destroy the library instance when done to free WASM memory. ```typescript // Always destroy when done to free WASM memory library.destroy(); ``` -------------------------------- ### PDFiumPage.getOriginalSize() Source: https://context7.com/hyzyla/pdfium/llms.txt Fetches the original dimensions of a PDF page in PDF points (1 pt = 1/72 inch), before any scaling is applied. This is useful for calculating accurate pixel dimensions based on a desired DPI. ```APIDOC ## `PDFiumPage.getOriginalSize()` — Get the original page dimensions Returns the page's native width and height in PDF points (1 pt = 1/72 inch) before any scaling is applied. ```typescript const document = await library.loadDocument(buff); const page = document.getPage(0); const { originalWidth, originalHeight } = page.getOriginalSize(); console.log(`${originalWidth} x ${originalHeight} pts`); // A4 page: "595 x 841 pts" (595 pt ≈ 210 mm, 841 pt ≈ 297 mm at 72 DPI) // Compute a target DPI manually: const targetDPI = 300; const scale = targetDPI / 72; const pixelWidth = Math.round(originalWidth * scale); // 2480 const pixelHeight = Math.round(originalHeight * scale); // 3508 const image = await page.render({ scale, render: 'sharp' }); console.log(image.width, image.height); // 2480 x 3508 document.destroy(); ``` ``` -------------------------------- ### PDFiumPage.getObject() Source: https://context7.com/hyzyla/pdfium/llms.txt Retrieves a typed PDFiumObject (text, path, image, shading, or form) at a specified index on a page. The type of the object can be checked using `obj.type` to narrow down to a specific subtype for further operations. ```APIDOC ## `PDFiumPage.getObject()` — Get a page object by index Returns a typed `PDFiumObject` (one of `PDFiumTextObject`, `PDFiumPathObject`, `PDFiumImageObject`, `PDFiumShadingObject`, `PDFiumFormObject`) at the given zero-based index. Check `object.type` to narrow to a specific subtype. ```typescript const page = document.getPage(0); const obj = page.getObject(0); console.log(obj.type); // "text" | "path" | "image" | "shading" | "form" if (obj.type === 'image') { // obj is now typed as PDFiumImageObject const rendered = await obj.render({ render: 'sharp' }); console.log(rendered.width, rendered.height); } ``` ``` -------------------------------- ### Iterate over all pages in a PDF document Source: https://context7.com/hyzyla/pdfium/llms.txt Use a generator function with `for...of` loop to iterate over all `PDFiumPage` instances in a document without manual index management. ```typescript for (const page of document.pages()) { console.log(`Processing page ${page.number + 1} of ${document.getPageCount()}`); // page is a PDFiumPage instance } ``` -------------------------------- ### Render PDFiumImageObject to various formats Source: https://context7.com/hyzyla/pdfium/llms.txt Decodes and renders an image object from a PDF page. Supports rendering to 'bitmap', 'sharp', or a custom async function. Returns image data along with width and height. ```typescript import { PDFiumLibrary, type PDFiumPageRenderOptions } from '@hyzyla/pdfium'; import { promises as fs } from 'fs'; import sharp from 'sharp'; const library = await PDFiumLibrary.init(); const buff = await fs.readFile('document.pdf'); const document = await library.loadDocument(buff); let imageIndex = 0; for (const page of document.pages()) { for (const obj of page.objects()) { if (obj.type === 'image') { // Render as PNG const { data, width, height } = await obj.render({ render: 'sharp' }); console.log(`Image ${imageIndex}: ${width}x${height} px`); await fs.writeFile(`image_${imageIndex}.png`, data); // Render as JPEG with compression const jpeg = await obj.render({ render: async (options: PDFiumPageRenderOptions) => sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4 }, }).jpeg({ quality: 80 }).toBuffer(), }); await fs.writeFile(`image_${imageIndex}.jpg`, jpeg.data); imageIndex++; } } } document.destroy(); library.destroy(); ``` -------------------------------- ### PDFiumImageObject.render() Source: https://context7.com/hyzyla/pdfium/llms.txt Renders an embedded image object from a PDF page into a specified format. It supports rendering to 'bitmap', 'sharp', or a custom async function, returning the image data along with its dimensions. ```APIDOC ## `PDFiumImageObject.render()` — Render an embedded image Decodes and renders an image object extracted from a PDF page to a specified format. Accepts the same `render` option as `page.render()` (`"bitmap"`, `"sharp"`, or a custom async function). Returns `{ data, width, height }`. ```typescript import { PDFiumLibrary, type PDFiumPageRenderOptions } from '@hyzyla/pdfium'; import { promises as fs } from 'fs'; import sharp from 'sharp'; const library = await PDFiumLibrary.init(); const buff = await fs.readFile('document.pdf'); const document = await library.loadDocument(buff); let imageIndex = 0; for (const page of document.pages()) { for (const obj of page.objects()) { if (obj.type === 'image') { // Render as PNG const { data, width, height } = await obj.render({ render: 'sharp' }); console.log(`Image ${imageIndex}: ${width}x${height} px`); await fs.writeFile(`image_${imageIndex}.png`, data); // Render as JPEG with compression const jpeg = await obj.render({ render: async (options: PDFiumPageRenderOptions) => sharp(options.data, { raw: { width: options.width, height: options.height, channels: 4 }, }).jpeg({ quality: 80 }).toBuffer(), }); await fs.writeFile(`image_${imageIndex}.jpg`, jpeg.data); imageIndex++; } } } document.destroy(); library.destroy(); ``` ```