### Node.js Quick Start Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Example of listing PDF pages and converting them to images in Node.js. Ensure you have a canvas adapter installed. ```typescript import { convert, listPages } from "pdftoimg-js"; // List page metadata const pages = await listPages("./document.pdf"); console.log(`Total pages: ${pages.length}`); // Convert to images const result = await convert("./document.pdf", { format: "png", pages: "1-3", dpi: 200, output: { outputDir: "./images" }, }); console.log(result.pages.map((p) => p.filePath)); ``` -------------------------------- ### Browser Quick Start Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Example of converting a file input to images in the browser. Configure the PDF.js worker for optimal performance. ```typescript import { convert, listPages, setPdfWorkerSrc } from "pdftoimg-js/browser"; // Configure PDF.js worker (recommended for performance) setPdfWorkerSrc( new URL("pdfjs-dist/build/pdf.worker.mjs", import.meta.url).toString() ); // Convert file input to images const result = await convert(file, { format: "png", output: { outputType: "blob" }, }); // Display the first page const url = URL.createObjectURL(result.pages[0].blob!); ``` -------------------------------- ### Install pdftoimg-js Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Install the pdftoimg-js package using npm. Node.js rendering also requires a canvas implementation. ```bash npm install pdftoimg-js ``` ```bash # Recommended (faster, no native dependencies) npm install @napi-rs/canvas # Alternative npm install canvas ``` -------------------------------- ### Generate Thumbnails Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Example demonstrating how to generate thumbnails from a PDF file. ```APIDOC ## Generate Thumbnails ### Description This example shows how to generate thumbnails for each page of a PDF file, with options for format and quality. ### Method `convert(pdfPath: string, options: ConvertOptions): Promise ### Parameters #### Path Parameters - **pdfPath** (string) - Required - Path to the PDF file. #### Options - **format** (string) - Required - Output image format for the main conversion. Accepts "png", "jpeg", or "webp". - **thumbnails** (object) - Optional - Configuration for generating thumbnails. - **scale** (number) - Required - Scale factor for the thumbnails. - **format** (string) - Required - Output image format for thumbnails. Accepts "png", "jpeg", or "webp". - **quality** (number) - Optional - JPEG/WebP quality (0-1) for thumbnails. ### Request Example ```ts const result = await convert("./document.pdf", { format: "png", thumbnails: { scale: 0.25, format: "jpeg", quality: 0.8, }, }); console.log(result.thumbnails); ``` ### Response #### Success Response - **ConvertResult** - An object containing the converted pages and thumbnails. - **thumbnails** (array) - An array of thumbnail image data. ``` -------------------------------- ### Custom Naming Pattern Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Example demonstrating how to customize the output file naming pattern. ```APIDOC ## Custom Naming Pattern ### Description This example shows how to define a custom naming pattern for the output image files, including zero-padding for page numbers. ### Method `convert(pdfPath: string, options: ConvertOptions): Promise ### Parameters #### Path Parameters - **pdfPath** (string) - Required - Path to the PDF file. #### Options - **naming** (object) - Optional - Configuration for file naming. - **pattern** (string) - Required - The naming pattern. Use `{page}` for page number and `{ext}` for extension. - **zeroPad** (number) - Optional - Number of digits for zero-padding the page number. ### Request Example ```ts const result = await convert("./document.pdf", { naming: { pattern: "page-{page}.{ext}", zeroPad: 3, }, }); // Output: page-001.png, page-002.png, ... ``` ### Response #### Success Response - **ConvertResult** - An object containing the conversion results. The output files will follow the specified naming pattern. ``` -------------------------------- ### Legacy API - Browser Usage Example Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Example of using the legacy `pdfToImg` function in a browser environment, typically for handling file uploads and displaying previews. ```typescript // Browser usage (pdftoimg-js/browser) // import { pdfToImg } from "pdftoimg-js/browser"; // const dataUrls = await pdfToImg(fileUrl, { pages: "all", imgType: "png" }); ``` -------------------------------- ### pdftoimg CLI Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt The `pdftoimg` binary exposes the full conversion API as CLI flags. Install the package globally or use `npx`. ```APIDOC ## CLI ### pdftoimg CLI — Convert PDFs from the command line The `pdftoimg` binary exposes the full conversion API as CLI flags. Install the package globally or use `npx`. ```bash # Basic conversion — all pages to PNG in ./output pdftoimg document.pdf # Convert pages 1-5 at 300 DPI to JPEG, output to ./images pdftoimg document.pdf --out ./images --format jpeg --dpi 300 --pages 1-5 --quality 0.9 # List page metadata as JSON pdftoimg document.pdf --list-pages --json # Generate thumbnails at 25% scale alongside full renders pdftoimg document.pdf --out ./out --thumbs 0.25 # Package all pages into a zip archive pdftoimg document.pdf --zip --out ./archives # Stream a single-page PDF's PNG bytes to stdout (pipe-friendly) pdftoimg document.pdf --stdout > page.png # Encrypted PDF, suppress logs, JSON output pdftoimg secret.pdf --password mySecret --quiet --json ``` ``` -------------------------------- ### In-Memory Output (Node.js) Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Example demonstrating how to convert a PDF to images and access the raw bytes in memory using Node.js. ```APIDOC ## In-Memory Output (Node.js) ### Description This example shows how to convert a PDF file to images and retrieve the raw image bytes directly in memory, without writing to disk. ### Method `convert(pdfPath: string, options: ConvertOptions): Promise ### Parameters #### Path Parameters - **pdfPath** (string) - Required - Path to the PDF file. #### Options - **format** (string) - Required - Output image format. Accepts "png", "jpeg", or "webp". - **quality** (number) - Optional - JPEG/WebP quality (0-1). Only applicable for "jpeg" and "webp" formats. - **output** (object) - Optional - Specifies output configuration. - **inMemory** (boolean) - Required - Set to `true` to keep output in memory. ### Request Example ```ts const result = await convert("./document.pdf", { format: "jpeg", quality: 0.85, output: { inMemory: true }, }); // Access raw bytes const bytes = result.pages[0].bytes; ``` ### Response #### Success Response - **ConvertResult** - An object containing the converted pages. - **pages** (array) - An array of page objects. - **bytes** (Buffer) - Raw image bytes for the page. ``` -------------------------------- ### Post-Processing Hook Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Example demonstrating how to use a post-processing hook to modify or inspect converted pages. ```APIDOC ## Post-Processing Hook ### Description This example shows how to use a `postProcess` hook, which is called after each page is converted. It allows for custom logic, such as modifying the page data or logging information. ### Method `convert(pdfPath: string, options: ConvertOptions): Promise ### Parameters #### Path Parameters - **pdfPath** (string) - Required - Path to the PDF file. #### Options - **postProcess** (function) - Optional - A callback function executed after each page conversion. It receives the page payload and context. - **payload** - The converted page data. - **context** - An object containing context information, including `pageNumber`. - The function should return the (potentially modified) payload. ### Request Example ```ts const result = await convert("./document.pdf", { postProcess: async (payload, context) => { console.log(`Processed page ${context.pageNumber}`); return payload; // Return modified payload if needed }, }); ``` ### Response #### Success Response - **ConvertResult** - An object containing the conversion results. The `postProcess` hook will have been executed for each page. ``` -------------------------------- ### Fetch and Convert Remote PDF in Browser Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Passing a URL string or URL object lets pdfjs-dist fetch the file directly, avoiding an intermediate ArrayBuffer copy. This example converts a remote PDF to WebP format with specified quality and page range. ```typescript import { convert, setPdfWorkerSrc } from "pdftoimg-js/browser"; setPdfWorkerSrc("/static/pdf.worker.mjs"); const result = await convert("https://example.com/report.pdf", { format: "webp", quality: 0.85, pages: "1-5", output: { outputType: "bytes" }, }); for (const page of result.pages) { console.log(`Page ${page.pageNumber}: ${page.bytes!.byteLength} bytes (WebP)`); } ``` -------------------------------- ### Legacy API - Single Page Data URL Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Use the legacy `pdfToImg` function to get a base64 data URL for the first page of a PDF. The output is suitable for direct use in HTML or for saving as a file. ```typescript import { pdfToImg, singlePdfToImg } from "pdftoimg-js"; import { writeFileSync } from "fs"; // Single page → string data URL const dataUrl = await pdfToImg("./document.pdf", { pages: "firstPage" }); const buffer = Buffer.from((dataUrl as string).split(",")[1], "base64"); writeFileSync("./first-page.png", buffer); ``` -------------------------------- ### Select Specific Pages using Range Strings Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt The `pages` option accepts "all", an array of numbers, or a compact range string. Ranges are parsed as inclusive segments; an omitted start defaults to 1 and an omitted end defaults to the last page. ```typescript import { convert } from "pdftoimg-js"; // Comma-separated ranges: pages 1, 2, 3, 5, and 9 through the end const result = await convert("./document.pdf", { pages: "1-3,5,9-", format: "png", output: { outputDir: "./out" }, }); // Array syntax const result2 = await convert("./document.pdf", { pages: [1, 3, 7], format: "png", output: { outputDir: "./out" }, }); ``` -------------------------------- ### pdftoimg CLI - Generate Thumbnails Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Generate thumbnails at 25% scale alongside full renders using the CLI. ```bash pdftoimg document.pdf --out ./out --thumbs 0.25 ``` -------------------------------- ### pdftoimg CLI - Basic Conversion Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Perform basic PDF to PNG conversion from the command line. All pages are converted and saved to the `./output` directory. ```bash pdftoimg document.pdf ``` -------------------------------- ### Thumbnails Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Generate a scaled companion image alongside each main page. ```APIDOC ## Thumbnails ### Description Generates a smaller, scaled version of each page (thumbnail) in addition to the main rendered image. This is useful for previews or contact sheets. ### Parameters #### thumbnails - `object` - Configuration object for thumbnail generation. - `scale` (number) - Required - The scale factor for the thumbnail relative to the main image (e.g., `0.25` for 25% size). - `format` (string) - Optional - The image format for the thumbnail (e.g., 'jpeg'). Defaults to the main `format`. - `quality` (number) - Optional - The quality setting for the thumbnail image. - `naming` (object) - Optional - Custom naming pattern for thumbnail files. - `pattern` (string) - Optional - Filename pattern, supports `{basename}`, `{page}`, `{pageNumber}`, `{ext}`. - `zeroPad` (number) - Optional - Number of zero-padding digits for page numbers. ### Response - `thumbnails` (array) - An array of objects, each representing a generated thumbnail, including its `pageNumber` and `filePath`. ``` -------------------------------- ### Options for Conversion and Page Listing Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Configuration options that can be passed to the `convert` and `listPages` functions. ```APIDOC ## Options ### Description Configuration options for controlling the conversion process. | Option | Type | Default | Description | |---|---|---|---| | `pages` | `"all"` \| `number[]` \| `string` | `"all"` | Specifies the pages to process. Can be a string like `"1-3,5,9-"`, an array of page numbers, or `"all"` for every page. | | `format` | `"png"` \| `"jpeg"` \| `"webp"` | `"png"` | The output image format. | | `quality` | `number` | `0.92` | The quality for JPEG and WebP formats (0 to 1). | | `scale` | `number` | `1` | A scaling factor applied to the rendering. Overrides `dpi`. | | `dpi` | `number` | `72` | Dots per inch for rendering. `72` DPI corresponds to a 1x scale. | | `maxConcurrency` | `number` | `4` | The maximum number of concurrent rendering operations. | | `background` | `string` | `"transparent"` | The background color for the output images. | | `password` | `string` | — | The password for encrypted PDF files. | | `pageRotation` | `number` | `0` | Additional rotation in degrees to apply to each page. | | `naming` | `NamingOptions` | `{basename}-p{page}.{ext}` | Defines the naming pattern for output files. | | `thumbnails` | `ThumbnailOptions` | — | Configuration for generating thumbnails. | | `postProcess` | `PostProcessHook` | — | A hook for custom post-processing of rendered images. | ### Node.js Output Options ```typescript output: { outputDir?: string; // Default: "output" inMemory?: boolean; // If true, returns image bytes instead of writing files } ``` ### Browser Output Options ```typescript output: { inMemory?: boolean; // Default: true outputType?: "blob" | "bytes"; // Default: "blob" } ``` ``` -------------------------------- ### Control Output File Name Patterns Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt The `naming` option accepts a `pattern` string with `{basename}`, `{page}`, `{pageNumber}`, and `{ext}` tokens, plus a `zeroPad` value to control zero-padding width. ```typescript import { convert } from "pdftoimg-js"; const result = await convert("./document.pdf", { format: "png", naming: { pattern: "page-{page}.{ext}", // e.g. page-001.png zeroPad: 3, }, output: { outputDir: "./renamed" }, }); console.log(result.pages.map((p) => p.filePath)); // [ 'renamed/page-001.png', 'renamed/page-002.png', ... ] ``` -------------------------------- ### pdftoimg CLI - List Page Metadata Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt List page metadata from a PDF in JSON format using the CLI. ```bash pdftoimg document.pdf --list-pages --json ``` -------------------------------- ### pdftoimg CLI - Encrypted PDF and Options Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Convert an encrypted PDF, suppress logs, and output in JSON format using the CLI. ```bash pdftoimg secret.pdf --password mySecret --quiet --json ``` -------------------------------- ### CLI Basic Conversion Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Perform basic PDF to image conversion using the command-line interface. Specify input, output directory, and format. ```bash # Basic conversion pdftoimg input.pdf --out ./images --format png # With options pdftoimg input.pdf --dpi 300 --pages 1-5 --format jpeg --quality 0.9 # List page metadata pdftoimg input.pdf --list-pages --json # Generate thumbnails pdftoimg input.pdf --thumbs 0.25 # Output to zip pdftoimg input.pdf --zip pdftoimg input.pdf --stdout > output.zip ``` -------------------------------- ### Custom Output Naming Pattern Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Customize the naming pattern for output image files. Supports placeholders like {page} and {ext}, with zero-padding options. ```typescript const result = await convert("./document.pdf", { naming: { pattern: "page-{page}.{ext}", zeroPad: 3, }, }); // Output: page-001.png, page-002.png, ... ``` -------------------------------- ### pdftoimg CLI - Advanced Conversion Options Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Convert specific pages (1-5) of a PDF to JPEG at 300 DPI, saving output to `./images` with a quality of 0.9. ```bash pdftoimg document.pdf --out ./images --format jpeg --dpi 300 --pages 1-5 --quality 0.9 ``` -------------------------------- ### Generate Thumbnails Alongside Main Pages Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Pass a `thumbnails` options object to produce a second render at a different scale/DPI in the same conversion pass. Thumbnail files follow a separate naming pattern and are returned in `result.thumbnails`. ```typescript import { convert } from "pdftoimg-js"; const result = await convert("./slides.pdf", { format: "png", dpi: 150, output: { outputDir: "./full" }, thumbnails: { scale: 0.25, // 25% of original size format: "jpeg", quality: 0.75, naming: { pattern: "{basename}-p{page}-thumb.{ext}" }, }, }); for (const thumb of result.thumbnails ?? []) { console.log(`Thumb page ${thumb.pageNumber}: ${thumb.filePath}`); } // Thumb page 1: full/slides-p1-thumb.jpg // Thumb page 2: full/slides-p2-thumb.jpg ``` -------------------------------- ### convert (Browser) Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Renders PDF pages using the browser's native canvas. Accepts a File, Blob, ArrayBuffer, Uint8Array, or a URL string/URL object. Returns blobs (default) or Uint8Array bytes via the output.outputType option. ```APIDOC ## convert (Browser) ### Description Converts a PDF file into images using browser-native rendering. This function can accept various input types including File objects, Blobs, ArrayBuffers, Uint8Arrays, or URL strings/objects. ### Method `convert(input, options)` ### Parameters #### input - `File | Blob | ArrayBuffer | Uint8Array | string | URL` - The PDF file or its source. #### options - `format` (string) - Required - The desired output image format (e.g., 'png', 'webp'). - `dpi` (number) - Optional - Dots per inch for rendering. - `maxConcurrency` (number) - Optional - Maximum concurrent rendering tasks. - `output` (object) - Optional - Configuration for output type and location. - `outputType` (string) - Optional - 'blob' (default) or 'bytes'. - `outputDir` (string) - Optional - Directory to save output files. - `inMemory` (boolean) - Optional - Whether to keep output in memory. - `quality` (number) - Optional - Quality setting for formats like WebP or JPEG. - `pages` (string | number[]) - Optional - Specifies which pages to convert (e.g., 'all', '1-5', [1, 3, 7]). - `thumbnails` (object) - Optional - Configuration for generating thumbnail images. - `scale` (number) - Optional - Scale factor for thumbnails. - `format` (string) - Optional - Thumbnail image format. - `quality` (number) - Optional - Thumbnail quality. - `naming` (object) - Optional - Naming convention for thumbnails. - `pattern` (string) - Optional - Filename pattern. - `zeroPad` (number) - Optional - Number of zero-padding digits. - `naming` (object) - Optional - Naming convention for main output files. - `pattern` (string) - Optional - Filename pattern. - `zeroPad` (number) - Optional - Number of zero-padding digits. - `postProcess` (function) - Optional - A callback function to process each rendered page. - `payload` (object) - The rendered page data (bytes or blob). - `context` (object) - Information about the page (number, dimensions, format, variant). ### Response - `pages` (array) - An array of objects, each representing a converted page with its data (blob or bytes) and file path if applicable. - `thumbnails` (array) - An array of thumbnail objects, if generated. ``` -------------------------------- ### pdfToImg (Legacy API) Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt The `pdfToImg` function is a backward-compatible shim for code written against v0.x. It returns base64-encoded data URLs (`data:image/png;base64,...`) rather than file paths or raw bytes. Supports `"firstPage"`, `"lastPage"`, `"all"`, page numbers, arrays, and `{startPage, endPage}` objects. ```APIDOC ## Legacy API (v0.x compatibility) ### pdfToImg — Return base64 data URLs (legacy Node.js and browser) The `pdfToImg` function is a backward-compatible shim for code written against v0.x. It returns base64-encoded data URLs (`data:image/png;base64,...`) rather than file paths or raw bytes. Supports `"firstPage"`, `"lastPage"`, `"all"`, page numbers, arrays, and `{startPage, endPage}` objects. ```ts import { pdfToImg, singlePdfToImg } from "pdftoimg-js"; import { writeFileSync } from "fs"; // Single page → string data URL const dataUrl = await pdfToImg("./document.pdf", { pages: "firstPage" }); const buffer = Buffer.from((dataUrl as string).split(",")[1], "base64"); writeFileSync("./first-page.png", buffer); // Multiple pages → string[] const images = await singlePdfToImg("./document.pdf", { pages: { startPage: 1, endPage: 3 }, imgType: "jpg", scale: 1.5, background: "white", intent: "print", }); (images as string[]).forEach((dataUrl, i) => { const buf = Buffer.from(dataUrl.split(",")[1], "base64"); writeFileSync(`./page-${i + 1}.jpg`, buf); }); // Browser usage (pdftoimg-js/browser) // import { pdfToImg } from "pdftoimg-js/browser"; // const dataUrls = await pdfToImg(fileUrl, { pages: "all", imgType: "png" }); ``` ``` -------------------------------- ### pdftoimg CLI - Zip Archive Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Package all converted PDF pages into a single zip archive using the CLI. ```bash pdftoimg document.pdf --zip --out ./archives ``` -------------------------------- ### Post-Processing Hook for Image Transformation Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt The `postProcess` callback runs after each page is encoded. It receives the raw `PostProcessPayload` (bytes or blob) and a `PostProcessContext` (page number, dimensions, format, variant). Return a modified payload to replace the output, or `void`/nothing to keep it unchanged. Works for both main pages and thumbnails. ```typescript import { convert } from "pdftoimg-js"; import sharp from "sharp"; // example third-party transform const result = await convert("./document.pdf", { format: "png", output: { inMemory: true }, postProcess: async (payload, context) => { if (context.variant === "main") { // Apply a grayscale transform with sharp const processed = await sharp(payload.bytes!) .grayscale() .toBuffer(); return { bytes: new Uint8Array(processed) }; } // Return nothing to keep thumbnails unchanged }, }); console.log(`Processed ${result.pages.length} pages`); ``` -------------------------------- ### convert (Browser, URL input) Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Fetch and convert a remote PDF directly by providing a URL. This avoids an intermediate ArrayBuffer copy. ```APIDOC ## convert (Browser, URL input) ### Description Fetches and converts a remote PDF file directly from a URL. This method is optimized to avoid an intermediate ArrayBuffer copy by letting the browser handle the fetching. ### Method `convert(url, options)` ### Parameters #### url - `string | URL` - The URL of the remote PDF file. #### options - `format` (string) - Required - The desired output image format (e.g., 'webp'). - `quality` (number) - Optional - Quality setting for formats like WebP or JPEG. - `pages` (string) - Optional - Specifies which pages to convert using range strings (e.g., '1-5'). - `output` (object) - Optional - Configuration for output type. - `outputType` (string) - Optional - 'blob' or 'bytes' (default). ### Response - `pages` (array) - An array of objects, each representing a converted page with its data (bytes in this case) and page number. ``` -------------------------------- ### Legacy API - Browser Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Use the `pdfToImg` function for backward compatibility in browser environments. It returns base64-encoded data URLs. ```APIDOC ## Legacy API - Browser ### Description This function provides a legacy interface for converting PDF to images in the browser. It returns base64-encoded data URLs. ### Method `pdfToImg(fileUrl: string, options?: LegacyOptions): Promise ### Parameters #### Path Parameters - **fileUrl** (string) - Required - URL or File object of the PDF. #### Options - **pages** (string | number | number[] | {startPage, endPage}) - Optional - Specifies which pages to convert. Accepts "firstPage", "lastPage", "all", a single page number, an array of page numbers, or a range object. - **imgType** (string) - Optional - The output image format. Accepts "png" or "jpg". - **scale** (number) - Optional - The scale factor for rendering the image. Defaults to 1. - **background** (string) - Optional - The background color of the output image. Defaults to "rgb(255,255,255)". - **intent** (string) - Optional - The rendering intent. Accepts "display", "print", or "any". Defaults to "display". - **maxWidth** (number) - Optional - Maximum width of the output image. - **maxHeight** (number) - Optional - Maximum height of the output image. ### Request Example ```ts import { pdfToImg } from "pdftoimg-js/browser"; const dataUrls = await pdfToImg(fileUrl, { pages: { startPage: 1, endPage: 3 }, imgType: "png", }); ``` ### Response #### Success Response - **string[]** - An array of base64-encoded data URLs, one for each converted page. ``` -------------------------------- ### Legacy API - Node.js Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Use the `pdfToImg` function for backward compatibility in Node.js environments. It returns base64-encoded data URLs. ```APIDOC ## Legacy API - Node.js ### Description This function provides a legacy interface for converting PDF to images in Node.js. It returns base64-encoded data URLs. ### Method `pdfToImg(pdfPath: string, options?: LegacyOptions): Promise ### Parameters #### Path Parameters - **pdfPath** (string) - Required - Path to the PDF file. #### Options - **pages** (string | number | number[] | {startPage, endPage}) - Optional - Specifies which pages to convert. Accepts "firstPage", "lastPage", "all", a single page number, an array of page numbers, or a range object. - **imgType** (string) - Optional - The output image format. Accepts "png" or "jpg". - **scale** (number) - Optional - The scale factor for rendering the image. Defaults to 1. - **background** (string) - Optional - The background color of the image. Defaults to "rgb(255,255,255)". - **intent** (string) - Optional - The rendering intent. Accepts "display", "print", or "any". Defaults to "display". - **maxWidth** (number) - Optional - Maximum width of the output image. - **maxHeight** (number) - Optional - Maximum height of the output image. ### Request Example ```ts import { pdfToImg } from "pdftoimg-js"; const dataUrl = await pdfToImg("./document.pdf", { pages: "firstPage", imgType: "jpg", scale: 2, }); ``` ### Response #### Success Response - **string[]** - An array of base64-encoded data URLs, one for each converted page. ``` -------------------------------- ### Page Range Syntax Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Select specific pages using flexible range strings or arrays. ```APIDOC ## Page Range Syntax ### Description Allows for flexible selection of pages to convert using the `pages` option. You can specify individual pages, ranges, or a combination. ### Parameters #### pages - `"all"` - Converts all pages. - `string` - A compact range string, e.g., `"1-3,5,9-"` which means pages 1 through 3, page 5, and pages 9 to the end. - `number[]` - An array of specific page numbers, e.g., `[1, 3, 7]`. ### Example Usage ```ts import { convert } from "pdftoimg-js"; // Using range string const result = await convert("./document.pdf", { pages: "1-3,5,9-", format: "png", output: { outputDir: "./out" }, }); // Using array syntax const result2 = await convert("./document.pdf", { pages: [1, 3, 7], format: "png", output: { outputDir: "./out" }, }); ``` ``` -------------------------------- ### convert (Node.js) Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Renders specified pages of a PDF file to image files on disk or to in-memory Uint8Array buffers. Supports various input types like file paths, Buffers, and streams. ```APIDOC ## convert (Node.js) ### Description Renders the specified pages of a PDF file to image files on disk or to in-memory `Uint8Array` buffers. Accepts a file path, `Buffer`, `Uint8Array`, `ArrayBuffer`, or a Node.js `Readable` stream as input. Returns a `ConversionResult` containing sorted page metadata, optional thumbnails, and render timings. ### Method `convert(input, options)` ### Parameters #### input - `input` (string | Buffer | Uint8Array | ArrayBuffer | ReadableStream) - The PDF input. Can be a file path, Buffer, Uint8Array, ArrayBuffer, or a Node.js Readable stream. #### options - `format` (string) - Output image format (e.g., "jpeg", "png", "webp"). - `quality` (number) - JPEG quality (0.1-1.0). - `pages` (string) - Comma-separated list of pages to convert (e.g., "1-3,5"). - `dpi` (number) - Dots per inch for rendering. - `maxConcurrency` (number) - Maximum concurrent rendering tasks. - `background` (string) - Background color for transparent images (e.g., "#ffffff"). - `output` (object) - Output configuration. - `outputDir` (string) - Directory to save output images. - `inMemory` (boolean) - If true, returns image bytes in memory instead of saving to disk. ### Request Example ```javascript import { convert } from "pdftoimg-js"; const result = await convert("./document.pdf", { format: "jpeg", quality: 0.9, pages: "1-3,5", dpi: 200, maxConcurrency: 4, background: "#ffffff", output: { outputDir: "./images" }, }); console.log(`Total pages in PDF: ${result.totalPages}`); for (const page of result.pages) { console.log(`Page ${page.pageNumber}: ${page.filePath} (${page.width}x${page.height})`); } ``` ### Response #### Success Response (`ConversionResult`) - `totalPages` (number) - Total number of pages in the PDF. - `pages` (Array) - Array of page metadata. - `pageNumber` (number) - The page number. - `filePath` (string) - The path to the saved image file (if `inMemory` is false). - `bytes` (Uint8Array) - The raw image bytes (if `inMemory` is true). - `width` (number) - The width of the rendered page in pixels. - `height` (number) - The height of the rendered page in pixels. - `timings` (object) - Rendering and encoding timings. - `render` (number) - Time taken for rendering in milliseconds. - `encode` (number) - Time taken for encoding in milliseconds. ### Response Example ```json { "totalPages": 10, "pages": [ { "pageNumber": 1, "filePath": "images/document-p1.jpg", "width": 1654, "height": 2339 } ], "timings": { "render": 150, "encode": 50 } } ``` ``` -------------------------------- ### pdftoimg CLI - Stream to Stdout Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Stream a single-page PDF's PNG bytes directly to stdout for piping into other tools. ```bash pdftoimg document.pdf --stdout > page.png ``` -------------------------------- ### RenderedPage Interface Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Defines the structure for information about a single rendered page or thumbnail. ```APIDOC ## RenderedPage ### Description Contains details about a single rendered page or thumbnail. ### Properties - `pageNumber` (number): The one-based index of the page. - `width` (number): The width of the rendered image in pixels. - `height` (number): The height of the rendered image in pixels. - `rotation` (number): The rotation applied to the page in degrees. - `filePath` (string, optional): The file path where the image is saved (Node.js only). - `blob` (Blob, optional): The image data as a Blob object (Browser only). - `bytes` (Uint8Array, optional): The image data as a byte array (when `inMemory` is true). ``` -------------------------------- ### Browser Legacy API Usage Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Use the legacy pdfToImg function in the browser, importing from the browser-specific path. It returns base64-encoded data URLs. ```typescript import { pdfToImg } from "pdftoimg-js/browser"; const dataUrls = await pdfToImg(fileUrl, { pages: { startPage: 1, endPage: 3 }, imgType: "png", }); ``` -------------------------------- ### Core Functions Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md These are the main functions provided by the pdftoimg-js library for converting PDFs and listing page information. ```APIDOC ## convert ### Description Converts a PDF file to a series of images. ### Method `convert(input, options?)` ### Parameters - `input` (string | Buffer | URL): The path to the PDF file, a Buffer containing PDF data, or a URL. - `options` (object, optional): Configuration options for the conversion process. ### Returns - `Promise`: A promise that resolves with the conversion results. ## listPages ### Description Lists metadata for each page in a PDF file. ### Method `listPages(input, options?)` ### Parameters - `input` (string | Buffer | URL): The path to the PDF file, a Buffer containing PDF data, or a URL. - `options` (object, optional): Configuration options for listing pages. ### Returns - `Promise`: A promise that resolves with an array of page information objects. ``` -------------------------------- ### Custom Naming Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Control the output file name patterns for converted images. ```APIDOC ## Custom Naming ### Description Provides control over the naming convention of the output image files. You can define a pattern and control zero-padding for page numbers. ### Parameters #### naming - `object` - Configuration object for file naming. - `pattern` (string) - Required - The filename pattern. Supports tokens like `{basename}`, `{page}`, `{pageNumber}`, and `{ext}`. - `zeroPad` (number) - Optional - The number of digits to use for zero-padding page numbers (e.g., `3` would result in `001`, `002`, etc.). ### Example Usage ```ts import { convert } from "pdftoimg-js"; const result = await convert("./document.pdf", { format: "png", naming: { pattern: "page-{page}.{ext}", // e.g. page-001.png zeroPad: 3, }, output: { outputDir: "./renamed" }, }); console.log(result.pages.map((p) => p.filePath)); // [ 'renamed/page-001.png', 'renamed/page-002.png', ... ] ``` ``` -------------------------------- ### Legacy API - Multiple Pages Data URLs Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Use the legacy `singlePdfToImg` function to obtain base64 data URLs for a range of PDF pages. Supports various image types, scaling, and background colors. ```typescript import { pdfToImg, singlePdfToImg } from "pdftoimg-js"; import { writeFileSync } from "fs"; // Multiple pages → string[] const images = await singlePdfToImg("./document.pdf", { pages: { startPage: 1, endPage: 3 }, imgType: "jpg", scale: 1.5, background: "white", intent: "print", }); (images as string[]).forEach((dataUrl, i) => { const buf = Buffer.from(dataUrl.split(",")[1], "base64"); writeFileSync(`./page-${i + 1}.jpg`, buf); }); ``` -------------------------------- ### Node.js Legacy API Usage Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Use the legacy pdfToImg function for backward compatibility in Node.js. It returns base64-encoded data URLs. ```typescript import { pdfToImg } from "pdftoimg-js"; const dataUrl = await pdfToImg("./document.pdf", { pages: "firstPage", imgType: "jpg", scale: 2, }); ``` -------------------------------- ### Convert PDF to Images in Browser Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Renders PDF pages using the browser's native canvas. Accepts a File, Blob, ArrayBuffer, Uint8Array, or a URL string/URL object. Returns blobs (default) or Uint8Array bytes via the output.outputType option. ```typescript import { convert, setPdfWorkerSrc, listPages } from "pdftoimg-js/browser"; setPdfWorkerSrc( new URL("pdfjs-dist/build/pdf.worker.mjs", import.meta.url).toString() ); // Triggered by an change event async function handleFileInput(file: File) { // Inspect pages first const info = await listPages(file); console.log(`PDF has ${info.length} pages`); // Render all pages as PNG blobs const result = await convert(file, { format: "png", dpi: 144, maxConcurrency: 2, output: { outputType: "blob" }, }); const container = document.getElementById("output")!; for (const page of result.pages) { const img = document.createElement("img"); img.src = URL.createObjectURL(page.blob!); img.alt = `Page ${page.pageNumber}`; container.appendChild(img); } } ``` -------------------------------- ### List PDF pages metadata (Node.js) Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Retrieves metadata (page number, dimensions, rotation) for all pages in a PDF without rendering. Useful for pre-flight checks or UI previews. Supports password-protected PDFs. ```typescript import { listPages } from "pdftoimg-js"; const pages = await listPages("./document.pdf", { dpi: 150, password: "secret123", }); console.log(`Total pages: ${pages.length}`); for (const p of pages) { console.log(`Page ${p.pageNumber}: ${Math.round(p.width)}x${Math.round(p.height)} rot=${p.rotation}`); } // Total pages: 10 // Page 1: 1240x1754 rot=0 // Page 2: 1240x1754 rot=90 ``` -------------------------------- ### DPI and Scale Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt `dpi` converts to a CSS-pixel scale factor (72 DPI = 1×). `scale` overrides `dpi` directly. Both options are available on `convert`, `listPages`, and `thumbnails`. ```APIDOC ## DPI and Scale — Control render resolution `dpi` converts to a CSS-pixel scale factor (72 DPI = 1×). `scale` overrides `dpi` directly. Both options are available on `convert`, `listPages`, and `thumbnails`. ```ts import { convert } from "pdftoimg-js"; // 300 DPI print-quality render const result = await convert("./brochure.pdf", { dpi: 300, format: "png", output: { outputDir: "./hires" }, }); // Explicit scale override (2× = 144 DPI equivalent) const result2 = await convert("./brochure.pdf", { scale: 2, format: "jpeg", quality: 0.92, output: { outputDir: "./scaled" }, }); ``` ``` -------------------------------- ### ConversionResult Interface Source: https://github.com/iqbal-rashed/pdftoimg-js/blob/main/README.md Defines the structure of the result returned by the `convert` function. ```APIDOC ## ConversionResult ### Description Represents the outcome of a PDF to image conversion. ### Properties - `pages` (RenderedPage[]): An array of objects, each representing a rendered page. - `thumbnails` (RenderedPage[], optional): An array of objects representing generated thumbnails. - `totalPages` (number): The total number of pages in the PDF. - `timings` ({ load: number, parse: number, render: number, encode: number, save: number }): An object containing timing information for different stages of the conversion process. ``` -------------------------------- ### Password-Protected PDFs Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Both `convert` and `listPages` accept a `password` option that is passed through to pdfjs-dist for decryption. ```APIDOC ## Password-Protected PDFs — Open encrypted PDFs Both `convert` and `listPages` accept a `password` option that is passed through to pdfjs-dist for decryption. ```ts import { convert, listPages } from "pdftoimg-js"; const pages = await listPages("./protected.pdf", { password: "mySecret" }); console.log(`Pages: ${pages.length}`); const result = await convert("./protected.pdf", { password: "mySecret", format: "png", output: { outputDir: "./out" }, }); ``` ``` -------------------------------- ### convert (Node.js, in-memory) Source: https://context7.com/iqbal-rashed/pdftoimg-js/llms.txt Converts PDF pages to raw image bytes in memory without writing files to disk, useful for streaming or further processing. ```APIDOC ## convert (Node.js, in-memory) ### Description When `output.inMemory` is `true`, pages are returned as `Uint8Array` bytes rather than being saved to disk. This is useful for streaming, further processing, or constructing zip archives without touching the filesystem. ### Method `convert(input, options)` ### Parameters #### input - `input` (string | Buffer | Uint8Array | ArrayBuffer | ReadableStream) - The PDF input. Can be a file path, Buffer, Uint8Array, ArrayBuffer, or a Node.js Readable stream. #### options - `format` (string) - Output image format (e.g., "jpeg", "png", "webp"). - `dpi` (number) - Dots per inch for rendering. - `output` (object) - Output configuration. - `inMemory` (boolean) - Must be `true` to retrieve bytes in memory. ### Request Example ```javascript import { convert } from "pdftoimg-js"; import { createReadStream } from "fs"; const stream = createReadStream("./report.pdf"); const result = await convert(stream, { format: "png", dpi: 150, output: { inMemory: true }, }); for (const page of result.pages) { console.log(`Page ${page.pageNumber}: ${page.bytes!.byteLength} bytes`); // Use page.bytes to upload, process, or buffer further } ``` ### Response #### Success Response (`ConversionResult`) - `pages` (Array) - Array of page metadata. - `pageNumber` (number) - The page number. - `bytes` (Uint8Array) - The raw image bytes. - `width` (number) - The width of the rendered page in pixels. - `height` (number) - The height of the rendered page in pixels. ### Response Example ```json { "pages": [ { "pageNumber": 1, "bytes": "", "width": 1240, "height": 1754 } ] } ``` ```