### Poppler Method Execution Flow (pdfToText Example) Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Details the steps involved when executing a Poppler method, using `pdfToText` as an example. It outlines signal extraction, option validation against accepted options and binary version, argument parsing, binary execution, and result handling including whitespace trimming. ```text poppler.pdfToText(file, outputFile, options, extras) ↓ 1. Extract signal from extras ↓ 2. Get accepted options via #getAcceptedOptions("pdfToText") ↓ 3. Get binary version via #getVersion(this.#pdfToTextBin) ↓ 4. Parse options via parseOptions(acceptedOptions, options, version) → Returns: [...args from options, file, outputFile] ↓ 5. Execute binary via execBinary(binary, args, file, options) ↓ 6. Handle result: - If maintainLayout option set, preserve whitespace - Otherwise trim stdout ↓ 7. Return Promise ``` -------------------------------- ### PDF to PostScript Conversion Examples Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/configuration.md Demonstrates different ways to convert PDF files to PostScript using the `Poppler.pdfToPs()` method with various configuration options. ```javascript const poppler = new Poppler(); // Default Level 2 PostScript await poppler.pdfToPs('document.pdf', 'output.ps'); ``` ```javascript // Level 1 for older printers await poppler.pdfToPs('document.pdf', 'output.ps', { level1: true }); ``` ```javascript // EPS format (single page) await poppler.pdfToPs('document.pdf', 'output.eps', { epsFile: true, firstPageToConvert: 1, lastPageToConvert: 1 }); ``` ```javascript // Level 3 with CID fonts await poppler.pdfToPs('document.pdf', 'output.ps', { level3: true }); ``` -------------------------------- ### Install Poppler binaries on Debian Source: https://github.com/fdawgs/node-poppler/blob/main/README.md On Debian-based Linux systems, install the necessary Poppler binaries using apt-get. These utilities are required for node-poppler to function. ```sh sudo apt-get install poppler-data poppler-utils ``` -------------------------------- ### Install node-poppler with npm Source: https://github.com/fdawgs/node-poppler/blob/main/README.md Install the node-poppler package using npm. This is the primary method for adding the library to your Node.js project. ```sh npm i node-poppler ``` -------------------------------- ### Install Poppler binaries on macOS with Homebrew Source: https://github.com/fdawgs/node-poppler/blob/main/README.md For macOS users, install the Poppler binaries using Homebrew. This command ensures the underlying Poppler utilities are available for the node-poppler wrapper. ```sh brew install poppler ``` -------------------------------- ### Get PDF Info with Metadata and URLs Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/configuration.md Retrieves comprehensive information from a PDF file, including metadata and URLs, formatted as JSON. This example demonstrates combining multiple options for detailed output. ```javascript // Get metadata and URLs const fullInfo = await poppler.pdfInfo('document.pdf', { printAsJson: true, printMetadata: true, printUrls: true }); ``` -------------------------------- ### CLI Tool for Poppler Operations Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md This example demonstrates how to build a command-line interface tool using Node-Poppler. It accepts a command, input file, and output file as arguments and executes the specified Poppler operation. ```javascript const { Poppler } = require('node-poppler'); const [command, input, output] = process.argv.slice(2); const poppler = new Poppler(); (async () => { try { const result = await poppler[command](input, output); console.log(result); } catch (error) { console.error(error.message); process.exit(1); } })(); ``` -------------------------------- ### Options Structure Example Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Illustrates the structure of options exported from modules within src/options/*.js. Each option maps to an object containing details like argument flag, type, and minimum version. ```javascript module.exports = { boundingBoxXhtml: { arg: "-bbox", type: "boolean", minVersion: "0.15.1" }, maintainLayout: { arg: "-layout", type: "boolean" }, // ... more options }; ``` -------------------------------- ### Check Poppler Version Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/configuration.md Provides the command-line instruction to check the installed Poppler version using the `pdfinfo` utility. ```bash pdfinfo -v # or any Poppler binary with -v flag ``` -------------------------------- ### PDF to HTML Conversion Examples Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/configuration.md Demonstrates basic and advanced PDF to HTML conversions using the Poppler library. Includes options for complex output, custom image formats, and single-page generation. ```javascript const poppler = new Poppler(); // Simple HTML conversion await poppler.pdfToHtml('document.pdf', 'output.html'); ``` ```javascript // Complex output with custom image format await poppler.pdfToHtml('document.pdf', 'output.html', { complexOutput: true, imageFormat: 'JPG' }); ``` ```javascript // Single page HTML await poppler.pdfToHtml('document.pdf', 'output.html', { singlePage: true, extractHidden: true }); ``` -------------------------------- ### Basic PDF Conversions with Node-Poppler Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Demonstrates converting a PDF to text, HTML, and PNG images using the Poppler class. Ensure Poppler is installed on your system. ```javascript const { Poppler } = require('node-poppler'); // Create instance (auto-detects Poppler path) const poppler = new Poppler(); // Convert PDF to text await poppler.pdfToText('document.pdf', 'output.txt'); // Convert PDF to HTML await poppler.pdfToHtml('document.pdf', 'output.html', { complexOutput: true }); // Convert PDF to PNG images await poppler.pdfToCairo('document.pdf', 'page-%d.png', { pngFile: true, resolutionXYAxis: 300 }); ``` -------------------------------- ### Handle Poppler Not Found Errors Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Use a try-catch block to gracefully handle cases where the Poppler executable is not found. Includes installation hints for different operating systems. ```javascript try { const poppler = new Poppler(); } catch (error) { console.error(error.message); // Install: apt-get install poppler-utils (Linux) // brew install poppler (macOS) // or npm install node-poppler-win32 (Windows) } ``` -------------------------------- ### Batch Processing with Node-Poppler Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Iterate over a list of PDF files and convert each to text asynchronously. Ensure Poppler is installed and accessible in your PATH. ```javascript const files = ['doc1.pdf', 'doc2.pdf', 'doc3.pdf']; for (const file of files) { await poppler.pdfToText(file, file.replace('.pdf', '.txt')); } ``` -------------------------------- ### Handle Poppler Binary Path Not Found Error Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/errors.md This snippet demonstrates how to catch the 'Unable to find Poppler binaries' error and provides platform-specific installation instructions. It also shows how to manually specify the Poppler path. ```javascript const { Poppler } = require('node-poppler'); try { // Try automatic detection const poppler = new Poppler(); console.log('Using Poppler from:', poppler.path); } catch (error) { if (error.message.includes('Unable to find')) { console.error('Poppler not found. Installing...'); // Manual installation instructions if (process.platform === 'win32') { console.log('Install via: npm install node-poppler-win32'); } else if (process.platform === 'darwin') { console.log('Install via: brew install poppler'); } else { console.log('Install via: apt-get install poppler-utils'); } } } // Or specify explicit path const poppler = new Poppler('/usr/local/bin/poppler'); ``` -------------------------------- ### Convert PDF to HTML using Promise Chain Source: https://github.com/fdawgs/node-poppler/blob/main/README.md Converts a PDF file to HTML format using a promise chain. This example demonstrates basic usage without specific page ranges. ```javascript const { Poppler } = require("node-poppler"); const file = "test_document.pdf"; const poppler = new Poppler(); const options = { firstPageToConvert: 1, lastPageToConvert: 2, }; poppler .pdfToHtml(file, undefined, options) .then((res) => { console.log(res); }) .catch((err) => { console.error(err); throw err; }); ``` -------------------------------- ### Check Option Version Constraint at Runtime Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md This JavaScript code demonstrates how the module checks if the installed Poppler version meets the minimum version requirement for a given option. It uses `semver.lt()` for comparison. ```javascript if (acceptedOption.minVersion && lt(version, acceptedOption.minVersion, { loose: true })) { invalidArgs.push(`'${key}' was introduced in v${acceptedOption.minVersion}, ...`); } ``` -------------------------------- ### Convert PDF to Text using Promise Chain Source: https://github.com/fdawgs/node-poppler/blob/main/README.md Converts a PDF file to plain text format using a promise chain. This example specifies an output file for the text content. ```javascript const { Poppler } = require("node-poppler"); const file = "test_document.pdf"; const poppler = new Poppler(); const options = { firstPageToConvert: 1, lastPageToConvert: 2, }; const outputFile = "test_document.txt"; poppler .pdfToText(file, outputFile, options) .then((res) => { console.log(res); }) .catch((err) => { console.error(err); throw err; }); ``` -------------------------------- ### Access Poppler Binary Path Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/poppler-class.md Retrieve the directory path where the Poppler binaries are located. This is useful for debugging or verifying the setup. ```javascript const poppler = new Poppler(); console.log(poppler.path); // e.g., "/usr/local/bin" or "C:\\Program Files\\poppler\\bin" ``` -------------------------------- ### Error Handling Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/COVERAGE_REPORT.txt Comprehensive guide to error handling, including standard error codes, common error scenarios, and best practices for managing failures. ```APIDOC ## Error Handling ### Description This section provides detailed information on error codes, common error scenarios, and strategies for robust error handling within the Node-Poppler library. ### Error Codes - 7 standard error codes are documented. ### Common Error Scenarios - 7 common error scenarios with corresponding solutions are provided. - Includes handling for AbortError and stderr output errors. - Differentiates between transient and permanent failures. ### Retry Patterns & Debugging - Retry patterns, including exponential backoff, are explained. - Error wrapping examples and debugging techniques are included. - Best practices for error handling are outlined. ### Documentation Location Detailed information is available in `errors.md`. ``` -------------------------------- ### Check Poppler Binary Version and Use Version-Safe Options Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/errors.md Verifies the installed Poppler binary version and uses options compatible with it to avoid 'Invalid option provided for the current version of the binary' errors. Requires 'node:child_process'. ```javascript const poppler = new Poppler(); // Check binary version const pdfinfo = require('node:child_process').spawnSync('pdfinfo', ['-v']); console.log(pdfinfo.stderr.toString()); // Shows version // Use version-safe options try { await poppler.pdfToHtml('document.pdf', 'output.html', { dataUrls: true // Requires Poppler >= 0.75.0 }); } catch (error) { if (error.message.includes('introduced in')) { console.error('Poppler version too old for this option'); console.error('Install newer Poppler version'); } } ``` -------------------------------- ### Implementing Timeouts for PDF Operations Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Set a timeout for PDF conversion operations to prevent indefinite hangs. This example uses Promise.race to either complete the operation or reject after a specified duration. ```javascript const promise = poppler.pdfToText('document.pdf', 'output.txt'); const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 30000) ); await Promise.race([promise, timeoutPromise]); ``` -------------------------------- ### Batch Process PDFs Sequentially and in Parallel Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Process multiple PDF files either sequentially or in parallel with a concurrency limit. The parallel example uses the 'p-limit' library to control the number of concurrent operations. ```javascript const files = ['doc1.pdf', 'doc2.pdf', 'doc3.pdf']; // Sequential for (const file of files) { await poppler.pdfToText(file, file.replace('.pdf', '.txt')); } // Parallel (with limit) const pLimit = require('p-limit'); const limit = pLimit(3); await Promise.all( files.map(file => limit(() => poppler.pdfToText(file, file.replace('.pdf', '.txt'))) ) ); ``` -------------------------------- ### Implementing Error Handling for PDF Operations Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Provides an example of using a try-catch block to handle potential errors during PDF processing, with specific checks for common issues like file not found or password requirements. ```javascript try { await poppler.pdfToText('document.pdf', 'output.txt'); } catch (error) { if (error.message.includes('opening a PDF file')) { console.error('File not found'); } else if (error.message.includes('permissions')) { console.error('PDF requires password'); } } ``` -------------------------------- ### Manage Version-Specific Options Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Be aware of Poppler version compatibility for certain options. Check your installed version with 'pdfinfo -v' and consider using version-safe alternatives or updating Poppler. ```javascript // Check installed version: pdfinfo -v // Update if needed to use newer options // Or use version-safe options await poppler.pdfToHtml('doc.pdf', 'out.html', { // dataUrls: true, // Skip if Poppler < 0.75.0 complexOutput: true // Supported in all versions }); ``` -------------------------------- ### Parallel Processing with Concurrency Limit Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Process multiple PDF files in parallel using p-limit to control concurrency. This prevents overwhelming the system with too many simultaneous operations. Install 'p-limit' via npm. ```javascript const pLimit = require('p-limit'); const limit = pLimit(3); await Promise.all( files.map(file => limit(() => poppler.pdfToText(file, file.replace('.pdf', '.txt'))) ) ); ``` -------------------------------- ### Poppler Class Methods Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/COVERAGE_REPORT.txt The Poppler class is the main entry point for interacting with the library. It exposes 12 public methods for PDF manipulation, each with detailed parameter, return type, error, and example documentation. ```APIDOC ## Poppler Class Methods ### Description The Poppler class provides a programmatic interface to interact with PDF files. It offers a suite of methods for various PDF operations, including attaching metadata, extracting information, converting formats, and merging/separating documents. ### Methods - pdfAttach() - pdfDetach() - pdfFonts() - pdfImages() - pdfInfo() - pdfSeparate() - pdfToCairo() - pdfToHtml() - pdfToPpm() - pdfToPs() - pdfToText() - pdfUnite() ### Parameters Detailed parameter tables for each method are available in `poppler-class.md`. ### Return Type Return type documentation for each method is available in `poppler-class.md`. ### Error Handling Error documentation for each method is available in `poppler-class.md` and detailed in `errors.md`. ### Code Examples Code examples for each method are available in `poppler-class.md` and `quick-reference.md`. ``` -------------------------------- ### Poppler Class Initialization Flow Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Illustrates the sequence of operations when a new Poppler instance is created. It covers binary path detection, path normalization, resolution of all Poppler binaries, and internal cache initialization. The constructor optionally accepts a binary path. ```text new Poppler(binPath?) ↓ 1. Detect binary path: - If binPath provided, use it - Else run `which pdfinfo` (or `where` on Windows) - If Windows and not found, try node-poppler-win32 package - Throw if no binaries found ↓ 2. Store normalized path ↓ 3. Resolve paths to all 12 binaries: - pdfattach, pdfdetach, pdffonts, pdfimages, - pdfinfo, pdfseparate, pdftocairo, pdftohtml, - pdftoppm, pdftops, pdftotext, pdfunite ↓ 4. Initialize internal caches: - #binVersions (Map) - #acceptedOptions (Map) ↓ 5. Return Poppler instance ``` -------------------------------- ### Outputting to Stdout Instead of a File Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Demonstrates how to receive output directly as a string (for text) or a Buffer (for binary formats) by omitting the outputFile parameter. ```javascript // Get text directly instead of writing file const text = await poppler.pdfToText('document.pdf', undefined); ``` ```javascript // Binary output for image/PDF formats const pdfBuffer = await poppler.pdfToCairo('document.pdf', undefined, { pdfFile: true }); ``` -------------------------------- ### Build Project with npm Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Use this command to build the project. It runs the TypeScript compiler to generate type definitions. ```bash npm run build ``` -------------------------------- ### Instantiate Poppler Class Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/poppler-class.md Create a new Poppler instance. If no path is provided, it attempts to find binaries in the system's PATH. On Windows, it may use bundled binaries if local ones are not found. ```javascript const { Poppler } = require('node-poppler'); // Use system-installed binaries (found via PATH) const poppler = new Poppler(); // Specify custom binary path const customPoppler = new Poppler('/usr/local/bin/poppler'); ``` -------------------------------- ### Configuration Options Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/COVERAGE_REPORT.txt The library supports extensive configuration through options for its methods. Over 244 individual options are documented, covering details like type, default values, and version compatibility. ```APIDOC ## Configuration Options ### Description This section details the configuration options available for various Poppler class methods. Each option is thoroughly documented, including its data type, default value, minimum supported version, and a descriptive explanation. ### Documented Options - PdfAttachOptions (2 options) - PdfDetachOptions (9 options) - PdfFontsOptions (6 options) - PdfImagesOptions (15 options) - PdfInfoOptions (16 options) - PdfSeparateOptions (3 options) - PdfToCairoOptions (44 options) - PdfToHtmlOptions (21 options) - PdfToPpmOptions (30 options) - PdfToPsOptions (29 options) - PdfToTextOptions (20 options) - PdfUniteOptions (1 option) - PopplerExtraOptions (1 option) ### Option Tables Detailed option tables with type, default, min version, and description are available in `configuration.md`. ### Usage Examples Usage examples for options are provided in `configuration.md` and `quick-reference.md`. ``` -------------------------------- ### Get PDF Info as Formatted Text Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/configuration.md Retrieves basic information from a PDF file and logs it as formatted text. This is the default output format. ```javascript const poppler = new Poppler(); // Get info as formatted text const info = await poppler.pdfInfo('document.pdf'); console.log(info); ``` -------------------------------- ### Convert PDF Pages to PNG Source: https://github.com/fdawgs/node-poppler/blob/main/README.md Converts specific pages of a PDF to PNG format using an async/await call. Ensure the 'node-poppler' package is installed. ```javascript const { Poppler } = require("node-poppler"); const file = "test_document.pdf"; const poppler = new Poppler(); const options = { firstPageToConvert: 1, lastPageToConvert: 2, pngFile: true, }; const outputFile = `test_document.png`; const res = await poppler.pdfToCairo(file, outputFile, options); console.log(res); ``` -------------------------------- ### Poppler Constructor Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/poppler-class.md Initializes a new Poppler instance. You can optionally provide a path to the Poppler binaries directory. If not provided, it attempts to find the `pdfinfo` binary in the PATH. ```APIDOC ## Poppler Constructor ### Description Initializes a new Poppler instance. You can optionally provide a path to the Poppler binaries directory. If not provided, it attempts to find the `pdfinfo` binary in the PATH. ### Parameters #### Path Parameters - **binPath** (string) - Optional - Path to the directory containing Poppler binaries. If not provided, the constructor attempts to find the `pdfinfo` binary in the PATH environment variable. On Windows, bundled binaries from `node-poppler-win32` are used if local binaries are unavailable. ### Throws - **Error** — If Poppler binaries cannot be found in the specified path, PATH environment variable, or bundled Windows package. ### Example ```javascript const { Poppler } = require('node-poppler'); // Use system-installed binaries (found via PATH) const poppler = new Poppler(); // Specify custom binary path const customPoppler = new Poppler('/usr/local/bin/poppler'); ``` ``` -------------------------------- ### Handle AbortError During Poppler Operation Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/errors.md This example shows how to use AbortController to cancel a Poppler operation and catch the resulting AbortError. It includes setting a timeout for cancellation. ```javascript const poppler = new Poppler(); const controller = new AbortController(); // Cancel after 5 seconds const timeoutId = setTimeout(() => controller.abort(), 5000); try { await poppler.pdfToText('large-document.pdf', 'output.txt', {}, { signal: controller.signal }); } catch (error) { if (error.name === 'AbortError') { console.log('Operation was cancelled'); } else { console.error('Conversion failed:', error.message); } } finally { clearTimeout(timeoutId); } ``` -------------------------------- ### Handling File Path and Buffer Input for PDF to Text Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Illustrates using both file paths (strings) and in-memory Buffers as input for the pdfToText method. The Buffer input is useful for encrypted PDFs or dynamic data. ```javascript // File path await poppler.pdfToText('document.pdf', 'output.txt'); ``` ```javascript // Buffer (useful for encrypted PDFs or dynamic data) const buffer = await readFile('document.pdf'); await poppler.pdfToText(buffer, 'output.txt', { userPassword: 'secret' }); ``` -------------------------------- ### Get PDF Information Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Use `pdfInfo` to retrieve metadata and structural information about a PDF. Options allow for JSON output, metadata printing, and URL listing. ```javascript pdfInfo(file, options, extras) // Output: printAsJson, printMetadata, printUrls, printDocStruct // Pages: firstPageToConvert, lastPageToConvert ``` -------------------------------- ### execBinary Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Executes a Poppler binary with specified arguments, an optional input file, and execution options. It returns the standard output content as a promise. ```APIDOC ## execBinary(binary, args, file, options) ### Description Execute a Poppler binary with given arguments and optional file input. ### Parameters - `binary` (string) - Required - Full path to binary executable - `args` (string[]) - Required - Command-line arguments - `file` (Buffer | string) - Optional - Input file path or Buffer - `options` (object) - Optional - Execution options: - `binaryOutput` (boolean) - Use binary encoding for stdout - `ignoreExitCode` (boolean) - Resolve on stdout presence regardless of exit code - `preserveWhitespace` (boolean) - Keep leading/trailing whitespace - `signal` (AbortSignal) - For cancellation ### Returns `Promise` - stdout content ``` -------------------------------- ### Get PDF Info as JSON Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/configuration.md Retrieves information from a PDF file and logs the 'title' property from the JSON output. Use the 'printAsJson: true' option for JSON output. ```javascript // Get info as JSON const jsonInfo = await poppler.pdfInfo('document.pdf', { printAsJson: true }); console.log(jsonInfo.title); ``` -------------------------------- ### OptionDetails Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/types.md Describes a single configuration option accepted by a Poppler binary, including its command-line argument, expected type, and version constraints. ```APIDOC ## Type Definition: OptionDetails ```javascript type OptionDetails = { arg: string; type: 'boolean' | 'number' | 'string'; minVersion?: string; maxVersion?: string; } ``` ### Description Describes a single configuration option accepted by a Poppler binary. | Field | Type | Required | Description | |---|---|---|---| | `arg` | string | Yes | The command-line argument to pass to the binary (e.g., `'-png'`, `'-f'`). Empty string for options like `printAsJson` that use no argument. | | `type` | `'boolean'` \| `'number'` \| `'string'` | Yes | Expected JavaScript type for the option value. | | `minVersion` | string | No | Minimum Poppler version (semantic version) required for this option. | | `maxVersion` | string | No | Maximum Poppler version beyond which this option is no longer supported. | ``` -------------------------------- ### Handle Errors with Try-Catch Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Use a try-catch block to gracefully handle potential errors during PDF processing. This example checks for specific error messages related to file opening or permissions. ```javascript try { await poppler.pdfToText('document.pdf', 'output.txt'); } catch (error) { if (error.message.includes('opening a PDF file')) { console.error('File not found'); } else if (error.message.includes('permissions')) { console.error('PDF requires password'); } else { console.error('Error:', error.message); } } ``` -------------------------------- ### Import Poppler Class (CommonJS) Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Demonstrates how to import the `Poppler` class using CommonJS module system, both as a destructured named export and a default export. ```javascript // Destructured named export const { Poppler } = require('node-poppler'); const poppler = new Poppler(); ``` ```javascript // Default export (same object) const Poppler = require('node-poppler').default; ``` -------------------------------- ### PdfToCairoOptions Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/types.md Comprehensive options for the `Poppler.pdfToCairo()` method, covering various output formats and conversion parameters. ```APIDOC ## PdfToCairoOptions **Type Definition** ```javascript type PdfToCairoOptions = { antialias?: 'best' | 'default' | 'fast' | 'good' | 'gray' | 'none' | 'subpixel'; cropBox?: boolean; cropHeight?: number; cropSize?: number; cropWidth?: number; cropXAxis?: number; cropYAxis?: number; duplex?: boolean; epsFile?: boolean; evenPagesOnly?: boolean; fillPage?: boolean; firstPageToConvert?: number; grayscaleFile?: boolean; iccFile?: string; jpegFile?: boolean; jpegOptions?: string; lastPageToConvert?: number; monochromeFile?: boolean; noCenter?: boolean; noCrop?: boolean; noShrink?: boolean; oddPagesOnly?: boolean; originalPageSizes?: boolean; ownerPassword?: string; paperHeight?: number; paperSize?: 'A3' | 'A4' | 'legal' | 'letter' | 'match'; paperWidth?: number; pdfFile?: boolean; pngFile?: boolean; printVersionInfo?: boolean; printDocStruct?: boolean; psFile?: boolean; psLevel2?: boolean; psLevel3?: boolean; quiet?: boolean; resolutionXAxis?: number; resolutionXYAxis?: number; resolutionYAxis?: number; scalePageTo?: number; scalePageToXAxis?: number; scalePageToYAxis?: number; singleFile?: boolean; svgFile?: boolean; tiffCompression?: 'deflate' | 'jpeg' | 'lzw' | 'none' | 'packbits'; tiffFile?: boolean; transparentPageColor?: boolean; userPassword?: string; } ``` **Description** Options for the `Poppler.pdfToCairo()` method. Comprehensive options for PDF conversion to multiple output formats (PNG, JPEG, TIFF, PDF, EPS, SVG, PS). ``` -------------------------------- ### Basic Node-Poppler Usage Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Instantiate the Poppler class, either automatically detecting the Poppler path or specifying a custom path. All methods are asynchronous. ```javascript const { Poppler } = require('node-poppler'); // Create instance (auto-detects Poppler path) const poppler = new Poppler(); // Or specify custom path const customPoppler = new Poppler('/usr/local/bin/poppler'); // All methods are async await poppler.pdfToText('input.pdf', 'output.txt'); ``` -------------------------------- ### Method Options Matrix Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/types.md A matrix detailing the options types and return types for each available Poppler method. ```APIDOC ## Method Options Matrix ### Description This matrix outlines the expected options type and the return type for each Poppler method. | Method | Options Type | Returns Type | |---|---|---| | `pdfAttach()` | `PdfAttachOptions` | `Promise` | | `pdfDetach()` | `PdfDetachOptions` | `Promise` | | `pdfFonts()` | `PdfFontsOptions` | `Promise` | | `pdfImages()` | `PdfImagesOptions` | `Promise` | | `pdfInfo()` | `PdfInfoOptions` | `Promise | string>` | | `pdfSeparate()` | `PdfSeparateOptions` | `Promise` | | `pdfToCairo()` | `PdfToCairoOptions` | `Promise` | | `pdfToHtml()` | `PdfToHtmlOptions` | `Promise` | | `pdfToPpm()` | `PdfToPpmOptions` | `Promise` | | `pdfToPs()` | `PdfToPsOptions` | `Promise` | | `pdfToText()` | `PdfToTextOptions` | `Promise` | | `pdfUnite()` | `PdfUniteOptions` | `Promise` | ``` -------------------------------- ### Configuring PDF to Text Conversion with Options Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Shows how to pass an options object to pdfToText to control specific conversion parameters like page ranges and layout maintenance. ```javascript await poppler.pdfToText('input.pdf', 'output.txt', { firstPageToConvert: 1, lastPageToConvert: 10, maintainLayout: true }); ``` -------------------------------- ### Ensure Output Directory Exists Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/errors.md Creates the output directory if it does not exist before writing the output file to prevent 'Output Directory Issues'. Requires 'node:fs' and 'node:path' modules. ```javascript const { mkdirSync, dirname } = require('node:fs'); const { resolve } = require('node:path'); const poppler = new Poppler(); const outputPath = resolve('results/output.txt'); // Ensure output directory exists mkdirSync(dirname(outputPath), { recursive: true }); try { await poppler.pdfToText('document.pdf', outputPath); } catch (error) { if (error.message.includes('opening an output file')) { console.error('Cannot write to:', outputPath); } } ``` -------------------------------- ### Get PDF Information using Node-Poppler Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/poppler-class.md Retrieves information from a PDF file using the pdfInfo method. Can return information as a formatted string or a JSON object. Supports specifying page ranges and options for the pdfinfo binary. ```javascript const poppler = new Poppler(); // Get PDF info as formatted text const info = await poppler.pdfInfo('document.pdf'); console.log(info); // Get PDF info as JSON object const jsonInfo = await poppler.pdfInfo('document.pdf', { printAsJson: true }); console.log(jsonInfo.title, jsonInfo.author); // Get specific page range info const rangeInfo = await poppler.pdfInfo('document.pdf', { firstPageToConvert: 1, lastPageToConvert: 5, printAsJson: true }); ``` -------------------------------- ### Configure PdfToText Extraction Options Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/configuration.md Demonstrates various configurations for pdfToText, including layout preservation, page range selection, bounding box generation, and hyphenation control. ```javascript const poppler = new Poppler(); // Extract with layout preservation await poppler.pdfToText('document.pdf', 'output.txt', { maintainLayout: true }); ``` ```javascript // Extract specific pages await poppler.pdfToText('document.pdf', 'output.txt', { firstPageToConvert: 1, lastPageToConvert: 5 }); ``` ```javascript // Extract with bounding boxes await poppler.pdfToText('document.pdf', 'output.html', { boundingBoxXhtmlLayout: true }); ``` ```javascript // Control hyphenation await poppler.pdfToText('document.pdf', 'output.txt', { removeHyphens: 'soft' }); ``` -------------------------------- ### parseOptions Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Validates and converts user-provided options into command-line arguments suitable for a Poppler binary. It can also perform version checks. ```APIDOC ## parseOptions(acceptedOptions, options, version) ### Description Validate and convert option objects to CLI arguments. ### Parameters - `acceptedOptions` (PopplerAcceptedOptions) - Required - Valid options for the binary - `options` (PopplerOptions) - Required - User-provided options - `version` (string) - Optional - Poppler version for version checks ### Returns `string[]` - CLI arguments ready for binary ### Throws `Error` if options are invalid or unsupported by version ``` -------------------------------- ### Import Poppler Class (TypeScript) Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Shows how to import the `Poppler` class in a TypeScript environment, leveraging the provided type definitions. ```typescript import { Poppler } from 'node-poppler'; const poppler = new Poppler(); ``` -------------------------------- ### Ensure Writable Output Directory Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Before writing output files, ensure the target directory exists and has the necessary write permissions. The 'recursive: true' option creates parent directories if they don't exist. ```javascript // Ensure output directory exists and is writable const { mkdirSync } = require('node:fs'); mkdirSync('output', { recursive: true }); await poppler.pdfToText('doc.pdf', 'output/text.txt'); ``` -------------------------------- ### PdfToPpmOptions Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/types.md Options for the `Poppler.pdfToPpm()` method. Controls image conversion (PPM, PGM, PBM, PNG, JPEG). ```APIDOC ## PdfToPpmOptions ### Description Options for the `Poppler.pdfToPpm()` method. Controls image conversion (PPM, PGM, PBM, PNG, JPEG). ### Parameters #### Optional Parameters - **antialiasFonts** (string) - 'no' | 'yes' - Font antialiasing: `'yes'` or `'no'` (default: `'yes'`). - **antialiasVectors** (string) - 'no' | 'yes' - Vector antialiasing: `'yes'` or `'no'` (default: `'yes'`). - **cropBox** (boolean) - Use crop box. - **cropHeight** (number) - Crop height. - **cropSize** (number) - Crop square size. - **cropWidth** (number) - Crop width. - **cropXAxis** (number) - Crop X coordinate. - **cropYAxis** (number) - Crop Y coordinate. - **defaultCmykProfile** (string) - DefaultCMYK ICC profile. - **defaultGrayProfile** (string) - DefaultGray ICC profile. - **defaultRgbProfile** (string) - DefaultRGB ICC profile. - **displayProfile** (string) - Display ICC profile. - **evenPagesOnly** (boolean) - Even pages only. - **firstPageToConvert** (number) - First page (default: 1). - **freetype** (string) - 'no' | 'yes' - FreeType font rasterizer: `'yes'` or `'no'` (default: `'yes'`). - **forcePageNumber** (boolean) - Force page number in filename. - **grayscaleFile** (boolean) - Grayscale output. - **hideAnnotations** (boolean) - Hide annotations. - **jpegCmyk** (boolean) - CMYK JPEG. - **jpegFile** (boolean) - Generate JPEG. - **jpegOptions** (string) - JPEG parameters. - **lastPageToConvert** (number) - Last page. - **monochromeFile** (boolean) - Monochrome output. - **oddPagesOnly** (boolean) - Odd pages only. - **ownerPassword** (string) - Owner password. - **overprint** (boolean) - Overprint emulation. - **pngFile** (boolean) - Generate PNG. - **printProgress** (boolean) - Print progress. - **printVersionInfo** (boolean) - Print version info. - **quiet** (boolean) - Suppress messages. - **resolutionXAxis** (number) - X resolution DPI (default: 150). - **resolutionXYAxis** (number) - X and Y resolution DPI (default: 150). - **resolutionYAxis** (number) - Y resolution DPI (default: 150). - **userPassword** (string) - User password. ### Used By - `Poppler.pdfToPpm()` ``` -------------------------------- ### Async/Await and Promise Chain for PDF to Text Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/README.md Demonstrates how to use Node-Poppler's pdfToText method with both async/await and traditional Promise chaining for asynchronous operations. ```javascript // Async/await const result = await poppler.pdfToText('input.pdf', 'output.txt'); ``` ```javascript // Promise chain poppler.pdfToText('input.pdf', 'output.txt') .then(result => console.log(result)) .catch(error => console.error(error)); ``` -------------------------------- ### Poppler Instance Property: path Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/poppler-class.md The `path` property returns the absolute path to the directory containing the Poppler binaries that the instance is using. ```APIDOC ## Poppler Instance Property: path ### Description The `path` property returns the absolute path to the directory containing the Poppler binaries that the instance is using. ### Type `string` (read-only) ### Example ```javascript const poppler = new Poppler(); console.log(poppler.path); // e.g., "/usr/local/bin" or "C:\Program Files\poppler\bin" ``` ``` -------------------------------- ### Use Valid Option Names Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/errors.md Ensures that only valid option names are used to prevent 'Invalid option provided' errors. Refer to configuration documentation for a list of valid options. ```javascript const poppler = new Poppler(); // Wrong: invalid option name try { await poppler.pdfToText('document.pdf', 'output.txt', { maintainLayout: true, unknownOption: true // ❌ Invalid }); } catch (error) { console.error('Invalid option:', error.message); } // Correct: check configuration.md for valid options await poppler.pdfToText('document.pdf', 'output.txt', { maintainLayout: true // ✓ Valid }); ``` -------------------------------- ### Output to Stdout Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Capture the output directly to stdout instead of writing to a file. This is useful for piping output to other commands or processes. For binary output, ensure the encoding is set to 'binary'. ```javascript // pdfToCairo, pdfToPs, pdfToText const result = await poppler.pdfToText('document.pdf', undefined); console.log(result); // For binary output (PDF, images) const { writeFile } = require('node:fs/promises'); const pdfOutput = await poppler.pdfToCairo('document.pdf', undefined, { pdfFile: true }); await writeFile('output.pdf', pdfOutput, { encoding: 'binary' }); ``` -------------------------------- ### Input PDF from Buffer Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/quick-reference.md Process a PDF directly from a buffer in memory instead of a file path. This is useful when the PDF content is generated or read from another source. ```javascript const { readFileSync } = require('node:fs'); const pdfBuffer = readFileSync('document.pdf'); // pdfFonts, pdfImages, pdfInfo, pdfToCairo, pdfToHtml, pdfToPpm, pdfToPs, pdfToText const text = await poppler.pdfToText(pdfBuffer, 'output.txt'); ``` -------------------------------- ### Cache Binary Versions Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/module-structure.md Demonstrates how Poppler instances cache binary versions. The first call to a method like pdfFonts fetches and caches the version, while subsequent calls use the cached value for efficiency. ```javascript const poppler = new Poppler(); // First call: fetches version, stores in cache await poppler.pdfFonts('doc1.pdf'); // Second call: uses cached version await poppler.pdfFonts('doc2.pdf'); ``` -------------------------------- ### Merge PDFs with Print Version Info Option Source: https://github.com/fdawgs/node-poppler/blob/main/_autodocs/configuration.md Demonstrates how to use the `pdfUnite` method with the `printVersionInfo` option set to false. This controls whether copyright and version information is printed during the merge process. ```javascript const poppler = new Poppler(); await poppler.pdfUnite( ['file1.pdf', 'file2.pdf', 'file3.pdf'], 'merged.pdf', { printVersionInfo: false } ); ```