### Clone Repository and Install Dependencies Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CONTRIBUTING.md Clone the project repository and install the necessary npm packages to get started. ```sh git clone https://github.com/dichovsky/pdf-to-png-converter.git cd pdf-to-png-converter npm ci ``` -------------------------------- ### Scripting Example: Version Check Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Bash command to display the installed version of the pdf-to-png-converter CLI tool. ```bash pdf-to-png --version ``` -------------------------------- ### Scripting Example: Help Information Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Bash command to display the help message and usage instructions for the pdf-to-png-converter CLI tool. ```bash pdf-to-png --help ``` -------------------------------- ### Install pdf-to-png-converter with Yarn Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/README.md Install the package using Yarn. Node.js 22.13 or higher is required. ```sh yarn add pdf-to-png-converter ``` -------------------------------- ### Specify Output Folder Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Examples for setting the directory where PNG files will be saved. The directory is created if it doesn't exist. ```bash pdf-to-png-converter document.pdf --output-folder ./output ``` ```bash pdf-to-png-converter document.pdf --output-folder /tmp/pngs ``` -------------------------------- ### Install pdf-to-png-converter with npm Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/README.md Install the package using npm. Node.js 22.13 or higher is required. ```sh npm install pdf-to-png-converter ``` -------------------------------- ### Display Package Version Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Check the installed version of the pdf-to-png-converter tool. ```bash $ pdf-to-png-converter --version v4.1.0 ``` -------------------------------- ### Usage Example for pdfToPng Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/types.md Demonstrates how to use the pdfToPng function with various configuration options. Ensure the 'pdf-to-png-converter' library is imported. ```typescript import { pdfToPng, VerbosityLevel } from 'pdf-to-png-converter'; const result = await pdfToPng('document.pdf', { viewportScale: 2.0, outputFolder: './output', processPagesInParallel: true, concurrencyLimit: 8, verbosityLevel: VerbosityLevel.WARNINGS, }); ``` -------------------------------- ### Convert with Timeout Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md This example demonstrates how to set a timeout for the conversion process using the `timeout` command, ensuring that the process does not run indefinitely. ```bash timeout 60 pdf-to-png-converter large.pdf --output-folder ./output --process-pages-in-parallel ``` -------------------------------- ### Specify PDF File Path Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Examples demonstrating how to specify the PDF file path using relative and absolute paths. ```bash pdf-to-png-converter document.pdf ``` ```bash pdf-to-png-converter /absolute/path/to/document.pdf ``` ```bash pdf-to-png-converter ./relative/path/document.pdf ``` -------------------------------- ### PngPageOutput: Content Example Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Example of PngPageOutput when returning page content as a buffer. This is the default behavior if `returnMetadataOnly` is false and `outputFolder` is not specified. ```typescript import { pdfToPng, PngPageOutput } from "pdf-to-png-converter"; const output: PngPageOutput[] = await pdfToPng(Buffer.from(pdfBuffer)); // output[0].content will be a Buffer containing the PNG data for the first page. ``` -------------------------------- ### Scripting Example: Parallel Conversion with Logging Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Bash script to convert multiple PDFs in parallel, with detailed logging enabled. ```bash INPUT_DIR="./batch_pdfs" OUTPUT_DIR="./batch_pngs" pdf-to-png --input-dir "$INPUT_DIR" --output-folder "$OUTPUT_DIR" --process-pages-in-parallel --concurrency-limit 8 --verbosity-level 5 ``` -------------------------------- ### Path Resolution Example Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/configuration.md Demonstrates how relative paths for options like outputFolder are resolved relative to the current working directory when pdfToPng() is called. ```typescript import { pdfToPng } from 'pdf-to-png-converter'; process.chdir('/data/pdfs'); const result = await pdfToPng('document.pdf', { outputFolder: './output', // Resolved relative to /data/pdfs }); ``` -------------------------------- ### JSON Metadata Output Example Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Illustrates the structure of the JSON output when using the `--return-metadata-only` option. ```json [ { "kind": "metadata", "pageNumber": 1, "name": "document_page_1.png", "width": 612, "height": 792, "rotation": 0, "content": null, "path": "" }, ... ] ``` -------------------------------- ### CLI Usage Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/SUMMARY.md Documentation for the command-line interface, including available options, usage patterns, and practical examples for scripting and batch processing. ```APIDOC ## Practical CLI Examples The `cli-reference.md` includes: - 7 real-world bash scripting examples - Error handling patterns - Timeout management - Batch processing - Concurrent PDF processing ``` -------------------------------- ### PngPageOutput: Metadata Example Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Example of PngPageOutput when returning metadata. This mode provides information about the PDF pages without the image content. ```typescript import { pdfToPng, PngPageOutput } from "pdf-to-png-converter"; const output: PngPageOutput[] = await pdfToPng(Buffer.from(pdfBuffer), { returnMetadataOnly: true, }); // output[0].metadata will contain information about the first page. ``` -------------------------------- ### Example Output Object Structure Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/README.md Illustrates the structure of the page objects returned by the pdfToPng function, including metadata and content details. ```javascript [ { kind: 'content', pageNumber: 1, // Page number in the PDF name: 'document_page_1.png', // PNG filename content: Buffer<...>, // PNG image data // undefined if returnPageContent=false path: '', // Empty string for in-memory and metadata results width: 612, // Image width in pixels (integer; floored from viewportScale) height: 792, // Image height in pixels (integer; floored from viewportScale) rotation: 0 // Page rotation in degrees: 0, 90, 180, or 270 }, // ... more pages ] ``` -------------------------------- ### PngPageOutput: File Variant Example Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Example of PngPageOutput when writing to files. This mode saves the generated PNGs to the specified output folder. ```typescript import { pdfToPng, PngPageOutput } from "pdf-to-png-converter"; const output: PngPageOutput[] = await pdfToPng(Buffer.from(pdfBuffer), { outputFolder: "./output", }); // output[0].filename will contain the path to the saved PNG file for the first page. ``` -------------------------------- ### Mocking pdfjs-dist Module Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CLAUDE.md Example of mocking the 'pdfjs-dist' module for testing. ```typescript // Mock pdfjs vi.mock('pdfjs-dist/legacy/build/pdf.mjs', () => ({ getDocument: vi.fn() })); ``` -------------------------------- ### File Not Found Error Handling Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Example of the error message displayed when the specified PDF file does not exist. ```bash $ pdf-to-png-converter missing.pdf --output-folder ./output Error: ENOENT: no such file or directory, stat 'missing.pdf' ``` -------------------------------- ### Scripting Example: Handling Password Protected PDFs Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Bash script to convert a password-protected PDF, providing the password via the CLI option. ```bash pdf-to-png --input-file ./secure.pdf --output-folder ./unlocked_pngs --pdf-file-password "mysecretpassword" ``` -------------------------------- ### TypeScript Module Resolution Example Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CLAUDE.md Demonstrates the correct way to import modules with `"module": "nodenext"` and `"moduleResolution": "node16"`. ```typescript import { normalizePath } from './normalizePath.js'; // correct import { normalizePath } from './normalizePath'; // incorrect — fails at runtime ``` -------------------------------- ### Output Folder Permission Error Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Example of an error message when the tool lacks the necessary permissions to create the output folder. ```bash $ pdf-to-png-converter document.pdf --output-folder /root/output Error: EACCES: permission denied, mkdir '/root/output' ``` -------------------------------- ### Scripting Example: Convert All PDFs in a Directory Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Bash script to find all PDF files in a directory and convert them to PNGs in a specified output folder. ```bash INPUT_DIR="./pdfs" OUTPUT_DIR="./pngs" for pdf_file in "$INPUT_DIR"/*.pdf; do if [ -f "$pdf_file" ]; then echo "Converting '$pdf_file' to PNGs..." pdf-to-png --input-file "$pdf_file" --output-folder "$OUTPUT_DIR" fi done ``` -------------------------------- ### Scripting Example: High-Resolution Conversion Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Bash script to convert a PDF with a higher viewport scale for detailed output, saving to a specific folder. ```bash pdf-to-png --input-file ./report.pdf --output-folder ./high_res_output --viewport-scale 3.0 ``` -------------------------------- ### CLI: Returning Metadata Only Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Use the `--return-metadata-only` flag to get JSON metadata for each page instead of PNG image files. ```bash pdf-to-png --input-file ./input.pdf --return-metadata-only ``` -------------------------------- ### Scripting Example: Convert Specific Pages with Metadata Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Bash script to convert pages 2 and 4 of a PDF, returning only metadata for those pages. ```bash pdf-to-png --input-file ./document.pdf --pages-to-process 2,4 --return-metadata-only --output-folder ./metadata_output ``` -------------------------------- ### Extract Specific Pages and Convert to JPEG Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md This example shows how to process only specific pages of a PDF and then convert the generated PNG images to JPEG format using the `convert` command. ```bash pdf-to-png-converter document.pdf --output-folder ./output --pages-to-process 1,5,10 for png in ./output/document_page_{1,5,10}.png; do convert "$png" "${png%.png}.jpg" done ``` -------------------------------- ### Resource Cleanup Example Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/README.md Ensures proper cleanup of PDF.js and canvas resources using a try-finally block. This is crucial for preventing memory leaks. ```typescript try { // ... use resources ... } finally { page.cleanup(); canvasFactory.destroy(canvasAndContext); pdfDocument.loadingTask.destroy(); } ``` -------------------------------- ### Quick Start: Convert PDF to PNGs (JavaScript) Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/README.md Convert a PDF file to PNG images and save them to an output folder. Existing files are not overwritten. ```javascript const { pdfToPng } = require('pdf-to-png-converter'); (async () => { const pngPages = await pdfToPng('document.pdf', { outputFolder: './output', }); console.log(`Converted ${pngPages.length} pages`); })(); ``` -------------------------------- ### API Reference Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/SUMMARY.md This section details all exported functions available for direct use by API consumers. It includes function signatures, parameter descriptions, return types, potential errors, and usage examples. ```APIDOC ## API Reference This section details all exported functions available for direct use by API consumers. It includes function signatures, parameter descriptions, return types, potential errors, and usage examples. Refer to `api-reference.md` for complete details. ``` -------------------------------- ### Quick Start: Convert PDF to PNGs (TypeScript) Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/README.md Convert a PDF file to PNG images using TypeScript, specifying output folder and verbosity level. Existing files are not overwritten. ```typescript import { pdfToPng, VerbosityLevel, type PngPageOutput } from 'pdf-to-png-converter'; const pngPages: PngPageOutput[] = await pdfToPng('document.pdf', { outputFolder: './output', verbosityLevel: VerbosityLevel.ERRORS, // 0=ERRORS, 1=WARNINGS, 5=INFOS }); ``` -------------------------------- ### run Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/api-reference.md Main CLI entry point. Parses `process.argv`, validates options, and executes conversion. This is an internal CLI utility function. ```APIDOC ## run ### Description Main CLI entry point. Parses `process.argv`, validates options, and executes conversion. ### Signature ```typescript export async function run(): Promise ``` ### Behavior - Parses `process.argv[2..]` via `parseArgs` with schema - Handles `--help` and `--version` flags - Validates all options through `buildPdfToPngOptions` - Calls `executeConversion` with logging - Exits with code 0 on success, 1 on error ``` -------------------------------- ### Display Help Message Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Show the usage instructions and available options for the CLI tool. ```bash $ pdf-to-png-converter --help Usage: pdf-to-png-converter [options] Options: --output-folder Folder path where PNG files will be written (required unless --return-metadata-only) ... ``` -------------------------------- ### Development and Testing Commands Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CLAUDE.md Run these commands for type-checking, fast testing, linting, and full test suites. ```bash npm run build:test # Type-check without emitting — run after edits npm run test:fast # Fast iteration: no coverage, dot reporter (preferred for agent loops) npx vitest run __tests__/.test.ts # Single test file npm run lint # ESLint src/**/*.ts npm test # Full: clean + build + tests + coverage (CI / pre-publish) ``` -------------------------------- ### Mocking Node FS Module Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CLAUDE.md Example of mocking the built-in 'node:fs' module for testing purposes. ```typescript // Mock node:fs vi.mock('node:fs', () => ({ promises: { readFile: vi.fn(), mkdir: vi.fn(), writeFile: vi.fn() }, })); ``` -------------------------------- ### Invalid PDF Error Handling Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Example of the error message when attempting to process a corrupted or invalid PDF file. ```bash $ pdf-to-png-converter invalid.pdf --output-folder ./output Error: ``` -------------------------------- ### Public API: pdfToPng() Data Flow Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/architecture.md Illustrates the data flow for the public pdfToPng function, from input parameters to normalized options and the final output. ```text ┌─ Input: pdfFile (string | ArrayBuffer | Uint8Array), props?: PdfToPngOptions │ ├─ [1] Normalize: normalizePdfToPngOptions(props) │ └─ Output: NormalizedPdfToPngOptions (validated, all defaults applied) │ ├─ [2] Call pdfToPngCore(pdfFile, normalizedOpts) │ └─ Output: PngPageOutput[] ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md The fundamental command structure for using the pdf-to-png-converter CLI. ```bash pdf-to-png-converter [options] ``` -------------------------------- ### Get Package Version Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/api-reference.md Reads the package version from the package.json file. Throws an error if package.json is missing or malformed. ```typescript export function getVersion(): string ``` -------------------------------- ### Handle Existing Output Files Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Demonstrates how to handle cases where output PNG files already exist. Existing files are not overwritten, and the command fails. Clearing the directory is a common workaround. ```bash # Clear the output folder before re-running rm -rf ./output pdf-to-png-converter document.pdf --output-folder ./output ``` -------------------------------- ### FilesystemSink Class Definition Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/types.md Implements the OutputSink interface for writing PNG pages to the local filesystem using exclusive-create mode ('wx'). It requires resolved and real output folder paths. ```typescript export class FilesystemSink implements OutputSink { constructor( private readonly resolvedOutputFolder: string, private readonly realOutputFolder: string ) public async write(name: string, content: Buffer): Promise } ``` -------------------------------- ### Get Page Metadata Function Signature Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CODEMAP.md Details the signature for the getPageMetadata asynchronous function, which retrieves metadata for a PDF page. ```typescript export async function getPageMetadata( pdf: PDFDocumentProxy, pageName: string, pageNumber: number, pageViewportScale: number, ): Promise ``` -------------------------------- ### Running Tests and Linting Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CONTRIBUTING.md Commands to execute tests, lint the code, perform type checking, and verify dependency licenses. ```sh npm test # build + run all tests with coverage npm run lint # ESLint across the repository using eslint.config.mjs npm run build:test # type-check src/ + __tests__/ (no emit) npm run build:strict # stricter dependency-boundary type-check npm run test:license # verify production dependency licenses ``` -------------------------------- ### CLI: --return-page-content Not Supported Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/errors.md The CLI does not support the `--return-page-content` flag because it cannot serialize binary PNG buffers to stdout. Use the library API for in-memory PNG buffers. ```bash # ❌ INVALID (CLI) $ pdf-to-png-converter doc.pdf --return-page-content # ✅ VALID (library API) const { pdfToPng } = require('pdf-to-png-converter'); const result = await pdfToPng('doc.pdf', { returnPageContent: true }); result.forEach(page => console.log(page.content)); ``` -------------------------------- ### Run a Single Test File Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CONTRIBUTING.md Execute a specific test file using npx and vitest. ```sh npx vitest run __tests__/.test.ts ``` -------------------------------- ### PDF Document Initialization Parameters Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CODEMAP.md Converts normalized PDF to PNG options into PDF.js document initialization parameters. Ensures all necessary parameters are correctly formatted for PDF.js. ```typescript export function propsToPdfDocInitParams(opts: NormalizedPdfToPngOptions): pdfApiTypes.DocumentInitParameters ``` -------------------------------- ### Configuration Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/SUMMARY.md Details on runtime constants and default configuration values used by the library. ```APIDOC ## Configuration Details on runtime constants and default configuration values used by the library. Refer to `configuration.md` for complete details. ``` -------------------------------- ### Build PDF to PNG Conversion Options Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/api-reference.md Parses raw CLI flags and positional arguments into validated conversion options and a PDF file path. It ensures a PDF path is provided and handles specific flag combinations. ```typescript export function buildPdfToPngOptions( values: ParsedValues, positionals: string[] ): { pdfFilePath: string; options: NormalizedPdfToPngOptions } ``` -------------------------------- ### Main CLI Entry Point Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/api-reference.md The main entry point for the CLI. It parses arguments, validates options, executes the conversion, and handles success or error exit codes. ```typescript export async function run(): Promise ``` -------------------------------- ### Get PDF Page Dimensions Only (JavaScript) Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/START-HERE.txt Retrieve only the metadata (dimensions) of PDF pages without rendering them to PNG. This is useful for pre-processing or analysis. ```javascript const metadata = await pdfToPng('document.pdf', { returnMetadataOnly: true, }); ``` -------------------------------- ### Fixing pagesToProcess Validation Errors Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/errors.md Provides examples of correct and incorrect usage for the pagesToProcess option. Each page number in the array must be a positive integer. ```typescript // ❌ INVALID await pdfToPng('doc.pdf', { pagesToProcess: [1, 2.5, 3] }); // Error: 2.5 not integer await pdfToPng('doc.pdf', { pagesToProcess: [0, 1, 2] }); // Error: 0 is <= 0 await pdfToPng('doc.pdf', { pagesToProcess: [-1, 1] }); // Error: -1 is <= 0 // ✅ VALID await pdfToPng('doc.pdf', { pagesToProcess: [1, 3, 5] }); // Pages 1, 3, 5 only await pdfToPng('doc.pdf', { pagesToProcess: [1] }); // Only page 1 await pdfToPng('doc.pdf'); // Omit to process all pages ``` -------------------------------- ### Error Handling Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/SUMMARY.md A comprehensive catalog of all error types, including their messages, conditions for triggering, source locations, and code examples for both error scenarios and their fixes. ```APIDOC ## Exhaustive Error Reference The `errors.md` file is the most comprehensive, with: - 24 distinct error types - Exact error messages from source - Trigger conditions - Source file and line numbers - Code examples showing the error - Code examples showing the fix - Organized by category for easy lookup ``` -------------------------------- ### Import the Main Function Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/README.md Import the primary pdfToPng function from the 'pdf-to-png-converter' package. This is the main entry point for converting PDFs to PNG images. ```typescript import { pdfToPng } from 'pdf-to-png-converter'; ``` -------------------------------- ### CLI: Setting Viewport Scale Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Adjust the rendering scale using `--viewport-scale`. Higher values result in larger, more detailed images. ```bash pdf-to-png --input-file ./input.pdf --output-folder ./output --viewport-scale 2.0 ``` -------------------------------- ### Extract Page Metadata Only Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/README.md Get page dimensions and rotation without rendering images. Useful for pre-processing checks like page counts or orientation. ```javascript // Inspect page dimensions and rotation without rendering any images const pages = await pdfToPng('document.pdf', { returnMetadataOnly: true, }); pages.forEach((page) => { console.log(`Page ${page.pageNumber}: ${page.width}x${page.height}px, rotation=${page.rotation}`); }); ``` -------------------------------- ### Module Dependency Graph Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/architecture.md Visualizes the dependencies between different modules within the src directory, including the main pdfToPng function and its core components, as well as the CLI entry point. ```text src/index.ts (public exports) ├── pdfToPng() [pdfToPng.ts] │ ├── normalizePdfToPngOptions() [normalizePdfToPngOptions.ts] │ └── pdfToPngCore() [pdfToPngCore.ts] │ ├── getPdfFileBuffer() [pdfInput.ts] │ ├── getPdfDocument() [pdfjsLoader.ts] │ │ └── propsToPdfDocInitParams() [propsToPdfDocInitParams.ts] │ │ └── normalizePath() [normalizePath.ts] │ ├── optionsToPageMode() [pageMode.ts] │ ├── resolvePageName() [pageOrchestrator.ts] │ ├── FilesystemSink [filesystemSink.ts] │ ├── processAndSavePage() [pageOrchestrator.ts] │ │ ├── getPageMetadata() [pageRenderer.ts] │ │ └── renderPdfPage() [pageRenderer.ts] │ └── processPagesWithSlidingWindow() [pdfToPngCore.ts] └── VerbosityLevel [types/verbosity.level.ts] CLI entry point: src/cli.ts ├── buildPdfToPngOptions() → normalizePdfToPngOptions() └── executeConversion() → pdfToPngCore() ``` -------------------------------- ### Get PDF Page Dimensions Only (CLI) Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/START-HERE.txt Command-line option to obtain only the metadata of PDF pages. Use the `--return-metadata-only` flag to disable rendering. ```bash $ pdf-to-png-converter document.pdf --return-metadata-only ``` -------------------------------- ### Advanced Configuration Options Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/README.md Sets detailed options for rendering, output, processing, security, and logging. Use this to customize the conversion process. ```typescript const options: PdfToPngOptions = { // Rendering viewportScale: 2.0, // 1–100, default 1 disableFontFace: true, // default true useSystemFonts: false, // default false enableXfa: true, // default true // Output outputFolder: './output', outputFileMaskFunc: (p) => `page_${p}.png`, // Processing pagesToProcess: [1, 2, 3], processPagesInParallel: true, concurrencyLimit: 4, // 1–16, default 4 // Content returnPageContent: true, returnMetadataOnly: false, // Security pdfFilePassword: 'secret', maxInputBytes: 256 * 1024 * 1024, // Logging verbosityLevel: VerbosityLevel.ERRORS, }; ``` -------------------------------- ### Get PDF File Buffer Function Signature Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CODEMAP.md Provides the signature for the getPdfFileBuffer asynchronous function, which retrieves a PDF file as a buffer, enforcing size limits. ```typescript export async function getPdfFileBuffer( pdfFile: string | ArrayBufferLike | Uint8Array, maxInputBytes: number, ): Promise ``` -------------------------------- ### Handle Existing Output Folder Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md When the output folder already exists, the tool will throw an EEXIST error. Clear the output folder or use a new one to resolve this. ```bash $ pdf-to-png-converter document.pdf --output-folder ./output (second run with same files) Error: EEXIST: file already exists, open './output/document_page_1.png' ``` ```bash rm -rf ./output pdf-to-png-converter document.pdf --output-folder ./output ``` -------------------------------- ### pdfToPngCore() Data Flow Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/architecture.md Details the step-by-step data flow within the pdfToPngCore function, including reading the PDF, loading the document, validation, page processing, and cleanup. ```text Input: pdfFile, NormalizedPdfToPngOptions [1] Read PDF Buffer getPdfFileBuffer(pdfFile, maxInputBytes) ├─ File path? → stat (check regular file) → readFile → post-check size ├─ Buffer? → copy to Uint8Array └─ Output: Uint8Array | ArrayBuffer [2] Load PDF Document getPdfDocument(buffer, normalizedOpts) ├─ Dynamic import: pdfjs-dist/legacy/build/pdf.mjs ├─ propsToPdfDocInitParams(normalizedOpts) │ └─ Map options to pdfjs DocumentInitParameters ├─ pdfjs.getDocument({ data, cMapUrl, ... }) └─ Output: PDFDocumentProxy [3] Validate & Plan ├─ Filter pages: validPagesToProcess = pages ∩ [1..numPages] ├─ Resolve output folder (if set and not returnMetadataOnly) ├─ Resolve all page names up-front: resolvePageName() for each page ├─ Detect duplicate filenames (case-insensitive) ├─ Create output folder (if writing) └─ Derive PageMode: optionsToPageMode() [4] Create Output Sink FilesystemSink(resolvedOutputFolder, realOutputFolder) if writing to disk [5] Process Pages For each page: processAndSavePage(pdfDocument, pageName, pageNumber, pageMode) ├─ Check PageMode: │ ├─ 'metadata' → getPageMetadata() │ │ ├─ getPage() │ │ ├─ getViewport(scale) │ │ ├─ Validate dimensions (non-zero and within pixel limit) │ │ └─ Return: MetadataPngPageOutput │ │ │ ├─ 'content' → renderPdfPage() │ │ ├─ getPage() │ │ ├─ getViewport(scale) │ │ ├─ Create canvas │ │ ├─ page.render(context) → Promise │ │ ├─ canvas.toBuffer('image/png') │ │ └─ Return: InMemoryPngPageOutput │ │ │ └─ 'file' → renderPdfPage() + sink.write() │ ├─ renderPdfPage() (same as 'content') │ ├─ sink.write(name, buffer) │ │ └─ savePNGfile() with path-traversal guard │ └─ Return: FilePngPageOutput with absolute path │ Sequential: process pages one-at-a-time Parallel: processPagesWithSlidingWindow() ├─ Maintain up to concurrencyLimit active promises ├─ Queue remaining pages └─ Collect results in original order [6] Cleanup finally: pdfDocument.loadingTask.destroy() Output: PngPageOutput[] ``` -------------------------------- ### PDF Document Resource Cleanup Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/architecture.md Ensures the PDF document's loading task is always destroyed, even if errors occur during page rendering or setup. This prevents memory leaks by releasing native resources. ```typescript try { // ... render pages ... } finally { await pdfDocument.loadingTask.destroy(); } ``` -------------------------------- ### pdfToPng() - Main Public Function Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/README.md The main public function for converting PDF files to PNG images. It takes options and returns a promise that resolves with the converted PNG data. ```APIDOC ## pdfToPng() ### Description Converts a PDF file to one or more PNG images. This is the primary function exposed by the library for programmatic use. ### Method `pdfToPng(options: PdfToPngOptions): Promise` ### Parameters #### Path Parameters None. #### Query Parameters None. #### Request Body None. (Function parameters are passed directly). ### Parameters Table - **options** (`PdfToPngOptions`) - Required - An object containing configuration options for the conversion process. ### Return Type `Promise` - A promise that resolves with an array of Buffers, where each Buffer represents a PNG image of a page from the PDF. ### Throws - **Validation Errors**: If input options are invalid (e.g., invalid `viewportScale`, `outputFolder`, `verbosityLevel`, `pagesToProcess`, `concurrencyLimit`, `maxInputBytes`). - **Input Handling Errors**: If the input file cannot be read or validated (e.g., oversized input, non-regular file). - **Output Path Errors**: If there are issues with output path validation (e.g., invalid path separators, non-string path, empty filename, duplicate filenames, path traversal attempts). - **Rendering Errors**: If page rendering fails (e.g., zero dimensions, pixel limit exceeded, invalid rotation, missing canvas factory). - **CLI-Specific Errors**: While this function is not directly CLI-related, underlying logic might share error types. ### Usage Example ```typescript import { pdfToPng } from 'pdf-to-png-converter'; import * as fs from 'fs'; async function convertPdf() { try { const pngBuffers = await pdfToPng({ filePath: './example.pdf', scale: 1.5, outputFolder: './output', verbosityLevel: 'info' }); pngBuffers.forEach((buffer, index) => { fs.writeFileSync(`./page-${index + 1}.png`, buffer); }); console.log('PDF converted to PNG successfully!'); } catch (error) { console.error('Error converting PDF:', error); } } convertPdf(); ``` ### Source File Path `./api-reference.md` (Conceptual, actual source file may vary) ``` -------------------------------- ### Implementing a Timeout for PDF Conversion Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/configuration.md Shows how to wrap the pdfToPng() function with a Promise.race to implement a custom timeout for potentially long-running conversions. ```typescript import { pdfToPng } from 'pdf-to-png-converter'; const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 60_000) ); const result = await Promise.race([ pdfToPng('document.pdf', { outputFolder: './output' }), timeout, ]); ``` -------------------------------- ### FilesystemSink Class Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CODEMAP.md Implements the OutputSink interface for writing output to the filesystem. It handles the logic for saving converted PNGs to disk. ```typescript export class FilesystemSink implements OutputSink { ``` ```typescript constructor() ``` ```typescript write ``` -------------------------------- ### buildPdfToPngOptions Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/api-reference.md Parses raw CLI flags into a validated `NormalizedPdfToPngOptions` and PDF file path. This is an internal CLI utility function. ```APIDOC ## buildPdfToPngOptions ### Description Parses raw CLI flags into a validated `NormalizedPdfToPngOptions` and PDF file path. ### Signature ```typescript export function buildPdfToPngOptions( values: ParsedValues, positionals: string[] ): { pdfFilePath: string; options: NormalizedPdfToPngOptions } ``` ### Parameters #### Path Parameters - **values** (ParsedValues) - Required - Parsed CLI flag values. - **positionals** (string[]) - Required - Positional arguments (should contain the PDF file path at index 0). ### Returns Object with `pdfFilePath` and validated `options`. ### Throws - `Error` — For all errors from `normalizePdfToPngOptions`, plus: - `Error` — When no PDF file path is provided - `Error` — When `--return-page-content` is specified (not supported by CLI) - `Error` — When neither `--return-metadata-only` nor `--output-folder` is specified ``` -------------------------------- ### Advanced PDF to PNG Conversion with Options Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/README.md Demonstrates advanced configuration for PDF to PNG conversion, including viewport scaling, font rendering, custom filenames, parallel processing, and logging levels. ```typescript import { pdfToPng, VerbosityLevel } from 'pdf-to-png-converter'; const pngPages = await pdfToPng('document.pdf', { // Rendering viewportScale: 2.0, // 2x zoom for higher resolution disableFontFace: false, // Use font face rendering useSystemFonts: true, // Fallback to system fonts // Output outputFolder: './pdf-images', outputFileMaskFunc: (pageNumber) => `page-${String(pageNumber).padStart(3, '0')}.png`, returnPageContent: true, // Performance processPagesInParallel: true, concurrencyLimit: 8, // Logging verbosityLevel: VerbosityLevel.WARNINGS, // Log warnings }); ``` -------------------------------- ### Architecture Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/SUMMARY.md An in-depth look at the library's design, module dependencies, data flow, concurrency model, and security considerations. ```APIDOC ## Architecture Documentation The `architecture.md` file provides understanding of: - Module dependencies with visual graph - Complete data flow from input to output - Design patterns (single validation boundary, PageMode discriminated union) - Concurrency model with memory analysis - Security considerations - Resource cleanup guarantees ``` -------------------------------- ### executeConversion Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/api-reference.md Executes the PDF-to-PNG conversion via `pdfToPngCore` and formats output. This is an internal CLI utility function. ```APIDOC ## executeConversion ### Description Executes the PDF-to-PNG conversion via `pdfToPngCore` and formats output. ### Signature ```typescript export async function executeConversion( pdfFilePath: string, options: NormalizedPdfToPngOptions, logInfo: (...msgs: unknown[]) => void, writeOutput?: (...msgs: unknown[]) => void ): Promise ``` ### Parameters #### Path Parameters - **pdfFilePath** (string) - Required - Path to PDF file. - **options** (NormalizedPdfToPngOptions) - Required - Validated options. - **logInfo** (Function) - Required - Logger for info messages. Called with conversion status. - **writeOutput** (Function) - Optional - Output writer (defaults to `console.log`). When `returnMetadataOnly`, outputs JSON. ### Behavior - If `returnMetadataOnly` is true, outputs JSON-formatted metadata to stdout - Otherwise, logs the number of successfully processed pages - Re-throws any pdfjs or rendering errors with context ``` -------------------------------- ### Exported Entry Points Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/configuration.md Defines the main library entry point, TypeScript definitions, and CLI executable path. ```json "exports": { ".": { "types": "./out/index.d.ts", "require": "./out/index.js", "default": "./out/index.js" } }, "main": "out/index.js", "types": "out/index.d.ts", "bin": { "pdf-to-png-converter": "out/cli.js" } ``` -------------------------------- ### Vitest Test Import Pattern Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CLAUDE.md Shows how to import testing utilities and the main function in Vitest tests. ```typescript import { expect, test } from 'vitest'; import { pdfToPng } from '../src/pdfToPng'; // direct src import import { comparePNG } from './comparePNG'; // shared PNG comparison helper ``` -------------------------------- ### Module System Configuration Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/configuration.md Indicates that the project is configured to use the CommonJS module system. ```json "type": "commonjs" ``` -------------------------------- ### PdfToPngOptions Interface Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CODEMAP.md Defines the available options for customizing the PDF to PNG conversion process. These options control aspects like scaling, font handling, and output details. ```APIDOC ## PdfToPngOptions ### Description Options for the `pdfToPng` conversion function. ### Fields - **viewportScale** (number) - Optional - The scale factor for the viewport. - **disableFontFace** (boolean) - Optional - If true, font faces will not be loaded. - **useSystemFonts** (boolean) - Optional - If true, system fonts will be used. - **enableXfa** (boolean) - Optional - If true, XFA forms will be enabled. - **pdfFilePassword** (string) - Optional - Password for encrypted PDF files. - **outputFolder** (string) - Optional - The folder where PNG files will be saved. - **outputFileMaskFunc** (function) - Optional - A function to generate the output file mask. ``` -------------------------------- ### Default Document Initialization Parameters Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/configuration.md Defines the default parameters for initializing PDF documents, including CMap URL, packing, and standard font data URL. ```typescript export const DOCUMENT_INIT_PARAMS_DEFAULTS: DocumentInitParameters = { cMapUrl: CMAP_RELATIVE_URL, cMapPacked: true, standardFontDataUrl: STANDARD_FONTS_RELATIVE_URL, }; ``` -------------------------------- ### Handle Large Pages with Viewport Scale Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md Demonstrates how to adjust the viewport scale to avoid errors when processing large PDF pages that might exceed pixel limits. ```bash # ❌ Error on large pages pdf-to-png-converter large.pdf --output-folder ./output --viewport-scale 50 # ✅ Reduce scale pdf-to-png-converter large.pdf --output-folder ./output --viewport-scale 2 ``` -------------------------------- ### Convert PDF to PNG Files (CLI) Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/START-HERE.txt This is the command-line equivalent for converting a PDF to PNG files. It takes the input PDF and an output folder as arguments. ```bash $ pdf-to-png-converter document.pdf --output-folder ./output ``` -------------------------------- ### Fixing Output Filename Being Empty String Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/errors.md Illustrates how to provide a non-empty string filename from `outputFileMaskFunc` to avoid errors. ```typescript // ❌ INVALID await pdfToPng('doc.pdf', { outputFolder: './output', outputFileMaskFunc: (p) => '', // Error: empty }); // ✅ VALID await pdfToPng('doc.pdf', { outputFolder: './output', outputFileMaskFunc: (p) => `page_${p}.png`, // Non-empty }); ``` -------------------------------- ### CLI: Parallel Processing Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/INDEX.txt Enable parallel processing with `--process-pages-in-parallel` to speed up conversion of multi-page PDFs. Control the number of concurrent workers with `--concurrency-limit`. ```bash pdf-to-png --input-file ./input.pdf --output-folder ./output --process-pages-in-parallel --concurrency-limit 4 ``` -------------------------------- ### Inspect Page Sizes using jq Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/cli-reference.md This command uses `jq` to parse the JSON metadata returned by the tool, extracting and displaying the page number, dimensions, and rotation for each page. ```bash pdf-to-png-converter document.pdf --return-metadata-only | jq '.[] | "\(.pageNumber): \(.width)×\(.height) px, \(.rotation)° rotation"' ``` -------------------------------- ### Default PDF to PNG Options Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/CLAUDE.md Default options for PDF to PNG conversion. Always extend these defaults using `??`. ```typescript PDF_TO_PNG_OPTIONS_DEFAULTS = { viewportScale: 1, disableFontFace: true, useSystemFonts: false, enableXfa: true, outputFileMask: 'buffer', // stem used when PDF is supplied as ArrayBufferLike pdfFilePassword: undefined, concurrencyLimit: 4, }; ``` -------------------------------- ### CLI: Missing Required Output Option Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/errors.md When using the CLI, you must specify either `--output-folder` to save images or `--return-metadata-only` to output JSON metadata to stdout. This error indicates neither was provided. ```bash # ❌ INVALID $ pdf-to-png-converter document.pdf # ✅ VALID (write PNG files) $ pdf-to-png-converter document.pdf --output-folder ./output # ✅ VALID (return JSON metadata to stdout) $ pdf-to-png-converter document.pdf --return-metadata-only ``` -------------------------------- ### Use pdfToPngCore in CLI Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/architecture.md The CLI directly invokes pdfToPngCore to avoid redundant option normalization and validation overhead. This ensures that options are processed only once before being passed to the core conversion logic. ```typescript // In cli.ts const results = await pdfToPngCore(pdfFilePath, options); ``` -------------------------------- ### Resolving Existing Output File Errors Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/errors.md Addresses the 'EEXIST: file already exists' error when using exclusive-create mode ('wx'). Solutions include clearing the output folder, using a new folder for each run, or implementing a custom filename function that ensures uniqueness. ```typescript import fs from 'fs'; import path from 'path'; // Clear the output folder before re-running const outputFolder = './output'; if (fs.existsSync(outputFolder)) { fs.rmSync(outputFolder, { recursive: true }); } // Or use a new folder each time const outputFolder = `./output-${Date.now()}`; // Or use a custom filename function await pdfToPng('doc.pdf', { outputFolder: './output', outputFileMaskFunc: (p) => `page_${p}_${Date.now()}.png`, }); ``` -------------------------------- ### Write PNG Page to Disk Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/api-reference.md Writes a PNG page to disk and returns its absolute path. Ensure the filename is flat and does not contain path separators. The content must be a Buffer. ```typescript async write(name: string, content: Buffer): Promise ``` -------------------------------- ### Execute PDF to PNG Conversion Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/api-reference.md Executes the core PDF to PNG conversion process. Outputs JSON metadata if `returnMetadataOnly` is true, otherwise logs the number of processed pages. Re-throws errors with context. ```typescript export async function executeConversion( pdfFilePath: string, options: NormalizedPdfToPngOptions, logInfo: (...msgs: unknown[]) => void, writeOutput?: (...msgs: unknown[]) => void ): Promise ``` -------------------------------- ### Fixing Input Path Not Being a Regular File Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/errors.md Illustrates how to provide a valid file path for PDF input, avoiding errors with non-regular files like FIFOs, sockets, or directories. ```typescript // ❌ INVALID await pdfToPng('/dev/zero'); // Error: character device await pdfToPng('/tmp/pipe', { /* ... */ }); // Error: FIFO await pdfToPng('/some/directory'); // Error: directory // ✅ VALID await pdfToPng('document.pdf'); // Regular file await pdfToPng('/absolute/path/to/document.pdf'); // Absolute path ``` -------------------------------- ### CLI: Convert All Pages Source: https://github.com/dichovsky/pdf-to-png-converter/blob/main/_autodocs/README.md Converts all pages of a PDF document to PNG images using the command-line interface. Specify the input PDF and output folder. ```bash # Convert all pages pdf-to-png-converter document.pdf --output-folder ./output ```