### Install pdf-merger-js Source: https://github.com/nbesli/pdf-merger-js/blob/master/README.md Commands to install the library locally or globally for CLI usage. ```bash npm install --save pdf-merger-js ``` ```bash npm install -g pdf-merger-js ``` -------------------------------- ### Install PDF Merger CLI Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Commands for installing the package globally or running it locally via npx. ```bash npm install -g pdf-merger-js ``` ```bash npm install pdf-merger-js npx pdf-merge [options] ``` -------------------------------- ### Check Version Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Displays the installed version of the CLI. ```bash pdf-merge -V # Output: 5.1.2 ``` -------------------------------- ### CLI Output Messages Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Examples of standard, verbose, and silent output modes. ```text Merged pages successfully into ``` ```text adding page(s) from to output... [repeated for each input] Saving merged output to ... Merged pages successfully into ``` ```text [No output to stdout] ``` -------------------------------- ### Simple Merge Example Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Basic command to merge two local PDF files. ```bash pdf-merge -o output.pdf input1.pdf input2.pdf ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Common command-line interface operations for merging PDF files, selecting pages, and managing output settings. ```bash # Basic merge pdf-merge -o output.pdf input1.pdf input2.pdf # With page selection pdf-merge -o output.pdf 'input1.pdf#1-3' 'input2.pdf#5' # Verbose output pdf-merge -v -o output.pdf input1.pdf input2.pdf # Silent mode pdf-merge -s -o output.pdf input1.pdf input2.pdf # From URLs pdf-merge -o output.pdf 'https://example.com/file.pdf#1-3' # Show version pdf-merge -V # Show help pdf-merge -h ``` -------------------------------- ### Merge PDFs in Node.js Source: https://github.com/nbesli/pdf-merger-js/blob/master/README.md Asynchronous example demonstrating how to add pages, set metadata, and save the resulting PDF. ```js import PDFMerger from 'pdf-merger-js'; var merger = new PDFMerger(); (async () => { await merger.add('pdf1.pdf'); //merge all pages. parameter is the path to file and filename. await merger.add('pdf2.pdf', 2); // merge only page 2 await merger.add('pdf2.pdf', [1, 3]); // merge the pages 1 and 3 await merger.add('pdf2.pdf', '4, 7, 8'); // merge the pages 4, 7 and 8 await merger.add('pdf3.pdf', '3 to 5'); //merge pages 3 to 5 (3,4,5) await merger.add('pdf3.pdf', '3-5'); //merge pages 3 to 5 (3,4,5) // Set metadata await merger.setMetadata({ producer: "pdf-merger-js based script", author: "John Doe", creator: "John Doe", title: "My live as John Doe" }); await merger.save('merged.pdf'); //save under given name and reset the internal document // Export the merged PDF as a nodejs Buffer // const mergedPdfBuffer = await merger.saveAsBuffer(); // fs.writeSync('merged.pdf', mergedPdfBuffer); })(); ``` -------------------------------- ### Specify Output File Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Examples of defining the destination path for the merged PDF. ```bash pdf-merge -o ./merged.pdf input1.pdf input2.pdf pdf-merge --output /tmp/result.pdf input1.pdf input2.pdf ``` -------------------------------- ### CLI usage for PDF merging Source: https://github.com/nbesli/pdf-merger-js/blob/master/README.md Command line interface help and example calls for merging local and remote PDF files. ```txt Usage: pdf-merge [options] merge multiple PDF documents, or parts of them, to a new PDF document Options: -V, --version output the version number -o, --output Merged PDF output file path -v, --verbose Print verbose output -s, --silent do not print any output to stdout. Overwrites --verbose -h, --help display help for command ``` ```bash pdf-merge --output ./merged.pdf ./input1.pdf#1-2 ./input2.pdf#1,2,5-7 ``` ```bash pdf-merge --verbose --output ./sample.pdf Testfile.pdf https://pdfobject.com/pdf/sample.pdf https://upload.wikimedia.org/wikipedia/commons/1/13/Example.pdf#2-3 ``` -------------------------------- ### Merge PDFs in React Source: https://github.com/nbesli/pdf-merger-js/blob/master/README.md Example of using the browser-specific build to merge File or Blob objects and display the result in an iframe. ```jsx import PDFMerger from 'pdf-merger-js/browser'; import React, { useEffect, useState } from 'react'; // files: Array of PDF File or Blob objects const Merger = (files) => { const [mergedPdfUrl, setMergedPdfUrl] = useState(); useEffect(() => { const render = async () => { const merger = new PDFMerger(); for(const file of files) { await merger.add(file); } await merger.setMetadata({ producer: "pdf-merger-js based script" }); const mergedPdf = await merger.saveAsBlob(); const url = URL.createObjectURL(mergedPdf); return setMergedPdfUrl(url); }; render().catch((err) => { throw err; }); () => setMergedPdfUrl({}); }, [files, setMergedPdfUrl]); return !data ? ( <>Loading ) : ( ); }; ``` -------------------------------- ### Error Cases for parsePagesString Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Examples of invalid inputs that cause the function to throw an Error. ```javascript parsePagesString() // Error: not a string parsePagesString(null) // Error: not a string parsePagesString({}) // Error: not a string parsePagesString('') // Error: empty string parsePagesString('-1to-3') // Error: negative numbers parsePagesString('1--3') // Error: double hyphen parsePagesString('1 until 3') // Error: invalid keyword ("until" not supported) parsePagesString('1-') // Error: incomplete range parsePagesString('10e3') // Error: scientific notation not supported ``` -------------------------------- ### Triggering Node.js Input Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Examples of inputs that trigger path or URL resolution errors in the Node.js environment. ```javascript await merger.add('./nonexistent.pdf'); // File not found, invalid URL await merger.add('not a path or url'); // Invalid format await merger.add('ht!tp://bad-url.com'); // Malformed URL ``` -------------------------------- ### Triggering Input Validation Errors in PDFMerger.add() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Examples of invalid inputs passed to the add method that trigger validation errors. ```javascript await merger.add(pdf, {}); // Object type not accepted await merger.add(pdf, 'invalid-pages'); // Invalid format await merger.add(pdf, NaN); // Not a valid number ``` -------------------------------- ### Triggering Browser Input Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Examples of inputs that trigger URL validation errors in the browser environment. ```javascript await merger.add('./local-file.pdf'); // File paths not supported in browser await merger.add('not a url'); // Invalid URL format await merger.add('ht!tp://bad.com'); // Malformed URL ``` -------------------------------- ### Parse Ranges with Hyphen Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Inclusive range syntax where both start and end are included. Whitespace around hyphens is allowed. ```javascript parsePagesString('1-3') // [1, 2, 3] parsePagesString(' 1-3 ') // [1, 2, 3] parsePagesString(' 1 - 3 ') // [1, 2, 3] parsePagesString('2-6') // [2, 3, 4, 5, 6] ``` -------------------------------- ### Triggering Input Type Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Examples of invalid input types passed to the add method that trigger type validation errors. ```javascript await merger.add(123); // Number not accepted await merger.add(true); // Boolean not accepted await merger.add({data: 'pdf'}); // Plain object not accepted ``` -------------------------------- ### Display Help Information Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Shows available options and usage instructions. ```bash pdf-merge -h # Displays usage and all options ``` -------------------------------- ### Running Tests Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Commands to execute the test suite for the project. ```bash npm test # Run all tests npm run test:watch # Watch mode ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Standard syntax for executing the merge command. ```bash pdf-merge [options] ``` -------------------------------- ### constructor() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Initializes a new PDFMerger instance for browser environments. ```APIDOC ## constructor() ### Description Creates a new PDFMerger instance configured for browser environments. The constructor initializes an empty internal PDF document and prepares the merger for page additions. ### Returns - **PDFMerger** - A new instance of the PDFMerger class. ``` -------------------------------- ### Add PDF Inputs Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/types.md Demonstrates adding various input types including file paths, URLs, and binary data. ```javascript // File path await merger.add('./document.pdf'); // URL await merger.add('https://example.com/file.pdf'); // Buffer const buffer = fs.readFileSync('./file.pdf'); await merger.add(buffer); // Uint8Array const uint8 = new Uint8Array([...]); await merger.add(uint8); ``` -------------------------------- ### Initialize PDFMergerBase Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMergerBase.md Constructor for the base class, initializing an empty internal PDF document. ```javascript constructor() ``` -------------------------------- ### Initialize PDFMerger Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md The constructor requires no parameters to initialize the library. ```javascript const merger = new PDFMerger(); ``` -------------------------------- ### CLI Tool Options Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md Available command-line arguments for the pdf-merge utility. ```bash pdf-merge [options] Options: -V, --version output the version number -o, --output Merged PDF output file path -v, --verbose Print verbose output -s, --silent do not print any output to stdout. Overwrites --verbose -h, --help display help for command ``` -------------------------------- ### Initialize internal PDF document Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMergerBase.md Ensures an internal PDFDocument instance exists, creating one with default metadata if necessary. ```javascript async _ensureDoc(): Promise ``` -------------------------------- ### Enable Verbose Output Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Displays detailed processing information during the merge. ```bash pdf-merge -v -o merged.pdf input1.pdf input2.pdf#1-3 # Output: # adding all pages from input1.pdf to output... # adding pages 1,2,3 from input2.pdf to output... # Saving merged output to merged.pdf... # Merged pages successfully into merged.pdf ``` -------------------------------- ### Add PDF Inputs in Browser Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/types.md Demonstrates adding various input types to the PDF merger instance in a browser environment. ```javascript // File from input element const file = document.querySelector('input[type="file"]').files[0]; await merger.add(file); // Blob from fetch const blob = await fetch('https://example.com/file.pdf').then(r => r.blob()); await merger.add(blob); // URL string await merger.add('https://example.com/file.pdf'); // Uint8Array const uint8 = new Uint8Array([...]); await merger.add(uint8); ``` -------------------------------- ### Project File Structure Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/INDEX.md The directory layout of the documentation files within the project. ```text output/ ├── INDEX.md # This file ├── README.md # Overview and quick reference ├── types.md # Type definitions ├── configuration.md # Configuration options ├── errors.md # Error reference ├── cli.md # CLI documentation └── api-reference/ ├── PDFMerger-Node.md # Node.js API ├── PDFMerger-Browser.md # Browser API ├── PDFMergerBase.md # Base class └── parsePagesString.md # Page parser ``` -------------------------------- ### Merge Remote Files with Verbose Output Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Download and merge multiple remote files while displaying detailed process information. ```bash pdf-merge --verbose --output sample.pdf \ Testfile.pdf \ https://pdfobject.com/pdf/sample.pdf \ 'https://upload.wikimedia.org/wikipedia/commons/1/13/Example.pdf#2-3' ``` -------------------------------- ### Verbose Mode for Debugging Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Run with the -v flag to see detailed information about the merge process. ```bash pdf-merge -v -o merged.pdf 'input1.pdf#1-3' 'input2.pdf#5' # Output: # adding pages 1,2,3 from input1.pdf to output... # adding page 5 from input2.pdf to output... # Saving merged output to merged.pdf... # Merged pages successfully into merged.pdf ``` -------------------------------- ### Initialize PDFMerger Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Create a new instance of the PDFMerger class for browser environments. ```javascript import PDFMerger from 'pdf-merger-js/browser'; const merger = new PDFMerger(); ``` -------------------------------- ### Default Metadata Initialization Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md Initial metadata values applied when the first page is added to a new PDF document. ```javascript producer: 'pdf-merger-js' creationDate: new Date() // Current date/time ``` -------------------------------- ### constructor() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Node.md Creates a new PDFMerger instance. The constructor initializes an empty internal PDF document and prepares the merger for page additions. ```APIDOC ## constructor() ### Description Creates a new PDFMerger instance. The constructor initializes an empty internal PDF document and prepares the merger for page additions. ### Returns - **PDFMerger instance** ``` -------------------------------- ### Initialize PDFMerger Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Instantiate a new merger object to begin processing PDF files. ```javascript new PDFMerger() ``` -------------------------------- ### Handle Promise in Node.js Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/types.md Retrieves a PDF as a Node.js Buffer instance. ```javascript const buffer = await merger.saveAsBuffer(); // buffer is Node.js Buffer instance // Can be passed to fs.writeFile(), sent in HTTP response, etc. ``` -------------------------------- ### Configure Page Selection Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md Use the add method to specify which pages to include from the input PDF. ```javascript await merger.add(input); // All pages await merger.add(input, 2); // Single page await merger.add(input, [1, 3, 5]); // Array of pages await merger.add(input, '1-3'); // Range format await merger.add(input, '1,3-5,7'); // Mixed format ``` -------------------------------- ### Overriding Default Metadata Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md Demonstrates how to update document metadata after the initial creation using setMetadata. ```javascript const merger = new PDFMerger(); await merger.add('input.pdf'); // At this point, producer is 'pdf-merger-js' await merger.setMetadata({ producer: 'CustomApp' }); // Now producer is 'CustomApp' ``` -------------------------------- ### Direct Usage of parsePagesString Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Shows how to import and use the function directly for advanced scenarios. ```javascript import { parsePagesString } from 'pdf-merger-js'; const pages = parsePagesString('1,5-7,10'); console.log(pages); // [1, 5, 6, 7, 10] ``` -------------------------------- ### Handle Missing Input Files Error Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Triggered when no input files are provided to the command. ```bash $ pdf-merge -o output.pdf Please provide at least one input file ``` -------------------------------- ### add(input, [pages]) Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Adds a PDF file to the merge queue, with optional page selection. ```APIDOC ## add(input, [pages]) ### Description Adds pages from a specified PDF input to the current merge session. ### Parameters - **input** (PdfInput) - Required - The PDF source (file path, URL, Buffer, Blob, etc.). - **pages** (Page Selection) - Optional - Specific pages to include (e.g., '1-3', [1, 3, 5]). ``` -------------------------------- ### Parse Mixed Formats Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Comma-separated list of individual pages and ranges in any order. Order is preserved from input. ```javascript parsePagesString('1-3,4') // [1, 2, 3, 4] parsePagesString(' 1-3 , 4 , 5') // [1, 2, 3, 4, 5] parsePagesString(' 1 - 3, 5-7 ') // [1, 2, 3, 5, 6, 7] parsePagesString(' 9,8,1 - 3, 5-6 ,8,9') // [9, 8, 1, 2, 3, 5, 6, 8, 9] parsePagesString('2-6,8') // [2, 3, 4, 5, 6, 8] parsePagesString('1,3-5,7') // [1, 3, 4, 5, 7] parsePagesString('11-13,5,8,16-18,14') // [11, 12, 13, 5, 8, 16, 17, 18, 14] ``` -------------------------------- ### Catching Fetch Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Demonstrates how to catch errors related to missing fetch support when loading PDFs from URLs. ```javascript try { await merger.add('https://example.com/file.pdf'); } catch (error) { if (error.message.includes('fetch is not defined')) { console.error('Fetch is not available; install a polyfill'); } } ``` -------------------------------- ### Merge with Page Selection Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Specify pages to include by appending a hash and range to the filename. Quote the argument to prevent shell interpretation of special characters. ```bash pdf-merge -o merged.pdf 'input.pdf#1-3' ``` ```bash # Single quotes prevent shell interpretation pdf-merge -o out.pdf 'input.pdf#1-3' 'input2.pdf#5,7' # Without quotes, some shells may interpret # as comment pdf-merge -o out.pdf input.pdf#1-3 # May fail depending on shell ``` -------------------------------- ### Applying Metadata to PDF Documents Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Metadata application requires at least one page to be added to the merger instance to persist correctly. ```javascript const merger = new PDFMerger(); // This doesn't error, but metadata won't persist if no pages are added await merger.setMetadata({ title: 'Test' }); // Metadata only persists if at least one page is added await merger.add('file.pdf'); ``` -------------------------------- ### Merge PDFs via Makefile Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Define build targets to automate PDF merging tasks using Make. ```makefile merge-pdfs: pdf-merge -v -o build/merged.pdf \ docs/intro.pdf \ 'docs/chapter1.pdf#1-20' \ 'docs/chapter2.pdf#1-25' \ docs/conclusion.pdf clean: rm -f build/merged.pdf ``` -------------------------------- ### Add Pages to PDFMerger Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Node.md Demonstrates various ways to add pages from local files, URLs, or Buffers using different page selection formats. ```javascript import PDFMerger from 'pdf-merger-js'; const merger = new PDFMerger(); // Add all pages from a local file await merger.add('./document.pdf'); // Add single page from file await merger.add('./document.pdf', 2); // Add multiple pages as array await merger.add('./document.pdf', [1, 3, 5]); // Add page range as string await merger.add('./document.pdf', '1-3'); // Add mixed ranges and individual pages await merger.add('./document.pdf', '1,3-5,7'); // Add pages using "to" syntax await merger.add('./document.pdf', '2 to 6'); // Add from URL await merger.add('https://example.com/file.pdf', '1-2'); // Add from Buffer const buffer = fs.readFileSync('./document.pdf'); await merger.add(buffer); ``` -------------------------------- ### Add pages to PDF Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/types.md Demonstrates various ways to specify pages when adding a PDF, using 1-indexed page numbers. ```javascript // Add all pages await merger.add(pdf, undefined); // or null, or no second argument // Single page await merger.add(pdf, 2); // Multiple as array await merger.add(pdf, [1, 3, 5]); // Range as string await merger.add(pdf, '1-3'); // Complex string await merger.add(pdf, '1,3-5,7'); // String array await merger.add(pdf, ['1', '2', '5']); ``` -------------------------------- ### Internal Usage in PDFMerger.add() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Demonstrates how the function is used internally when passing a string to the add method. ```javascript import PDFMerger from 'pdf-merger-js'; const merger = new PDFMerger(); // These all use parsePagesString internally: await merger.add('file.pdf', '1-3'); // Parsed: [1, 2, 3] await merger.add('file.pdf', '1,3-5,7'); // Parsed: [1, 3, 4, 5, 7] await merger.add('file.pdf', '2 to 6'); // Parsed: [2, 3, 4, 5, 6] ``` -------------------------------- ### Add PDF Pages Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Add pages from various sources like Files, Blobs, URLs, or Uint8Arrays. Pages are 1-indexed. ```javascript import PDFMerger from 'pdf-merger-js/browser'; const merger = new PDFMerger(); // Add from File input element const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; await merger.add(file); // Add multiple pages from file await merger.add(file, '1-3'); // Add from Blob (e.g., from fetch) const response = await fetch('https://example.com/document.pdf'); const blob = await response.blob(); await merger.add(blob); // Add from URL string await merger.add('https://example.com/file.pdf', [1, 2]); // Add from URL object const url = new URL('https://example.com/file.pdf'); await merger.add(url); // Add from Uint8Array const bytes = new Uint8Array([...]); await merger.add(bytes); ``` -------------------------------- ### Handle Promise in browser Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/types.md Retrieves a PDF as a Uint8Array instance in a browser environment. ```javascript const uint8 = await merger.saveAsBuffer(); // uint8 is Uint8Array instance // Can be sent to server, converted to Blob, etc. ``` -------------------------------- ### Catching Node.js Input Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Demonstrates how to catch and identify input errors in Node.js using error message matching. ```javascript try { await merger.add('./missing.pdf'); } catch (error) { if (error.message.includes('neither a valid file-path nor a valid URL')) { console.error('Input file or URL not found'); } } ``` -------------------------------- ### Add pages from source document Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMergerBase.md Loads a source PDF and copies specified pages into the current merged document using pdf-lib. ```javascript async _addPagesFromDocument(input: PdfInput, pages?: number[]): Promise ``` -------------------------------- ### Internal PDF Load Options Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md Hardcoded configuration for loading PDFs, enabling the merging of encrypted files without passwords. ```javascript { ignoreEncryption: true } ``` -------------------------------- ### Handle Browser File Input Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Process files selected via an HTML input element and export as a Blob. ```javascript import PDFMerger from 'pdf-merger-js/browser'; const merger = new PDFMerger(); const fileInput = document.querySelector('input[type="file"]'); for (const file of fileInput.files) { await merger.add(file); } const blob = await merger.saveAsBlob(); const url = URL.createObjectURL(blob); // Use for preview or download ``` -------------------------------- ### Import for TypeScript Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md Import the appropriate module based on the environment to utilize automatic type definitions. ```typescript import PDFMerger from 'pdf-merger-js'; // Types from: index.d.ts ``` ```typescript import PDFMerger from 'pdf-merger-js/browser'; // Types from: browser.d.ts ``` -------------------------------- ### URL and Mixed Inputs Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Merge remote PDF files via HTTP(S) URLs or combine them with local files. ```bash pdf-merge -o merged.pdf https://example.com/file.pdf pdf-merge -o merged.pdf 'https://example.com/file.pdf#1-3' ``` ```bash pdf-merge -o merged.pdf ./local.pdf 'https://example.com/remote.pdf#1-2' ``` -------------------------------- ### Basic PDF Merging Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Merge multiple local PDF files into a single output file. ```bash pdf-merge -o merged.pdf file1.pdf file2.pdf pdf-merge -o merged.pdf ./documents/a.pdf ./documents/b.pdf ``` -------------------------------- ### Handle Invalid Input File Error Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Triggered when a specified input file does not exist. ```bash $ pdf-merge -o output.pdf nonexistent.pdf An error occurred while merging the PDFs: [Error details] ``` -------------------------------- ### Merge PDFs in the Browser Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Import from the browser-specific entry point to handle file inputs and export merged PDFs as Blobs. ```javascript import PDFMerger from 'pdf-merger-js/browser'; const merger = new PDFMerger(); const file = document.querySelector('input[type="file"]').files[0]; await merger.add(file); const blob = await merger.saveAsBlob(); ``` -------------------------------- ### Handle Promise in browser Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/types.md Retrieves a PDF as a Blob object in a browser environment. ```javascript const blob = await merger.saveAsBlob(); // blob is Blob with MIME type 'application/pdf' // Can be downloaded, previewed, or uploaded ``` -------------------------------- ### Parse Multiple Pages Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Pages can be listed in any order. Duplicates are preserved. ```javascript parsePagesString('1,2,3') // [1, 2, 3] parsePagesString(' 1, 2, 3 ') // [1, 2, 3] parsePagesString('2,4,6') // [2, 4, 6] ``` -------------------------------- ### Merge from URLs Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Add remote PDF files directly via URL. ```javascript const merger = new PDFMerger(); await merger.add('https://example.com/file1.pdf'); await merger.add('https://example.com/file2.pdf', '1-3'); await merger.save('merged.pdf'); ``` -------------------------------- ### Handle Promise return Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/types.md Shows the result of methods that perform async operations without returning data. ```javascript const result = await merger.add('file.pdf'); // result is undefined ``` -------------------------------- ### Parse Page Selection Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Logic for extracting file paths and page ranges from input strings. ```javascript const [filePath, pagesString] = inputFile.split('#') const pages = pagesString ? parsePagesString(pagesString) : null await merger.add(filePath, pages) ``` -------------------------------- ### Implement General Error Handling Pattern Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Use a try-catch block to handle various error types during PDF merging operations. ```javascript import PDFMerger from 'pdf-merger-js'; const merger = new PDFMerger(); try { await merger.add('./input1.pdf'); await merger.add('./input2.pdf', '1-3'); await merger.setMetadata({ title: 'Merged PDF' }); await merger.save('./output.pdf'); } catch (error) { // Handle different error types if (error.message.includes('Invalid parameter')) { console.error('Invalid input parameters:', error.message); } else if (error.message.includes('not a valid')) { console.error('Invalid file or URL:', error.message); } else if (error.message.includes('EACCES')) { console.error('Permission denied:', error.message); } else { console.error('Unexpected error:', error.message); } } ``` -------------------------------- ### Define Type Definitions Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Reference types for input sources, metadata, and page selection patterns. ```typescript Uint8Array | ArrayBuffer | Blob | URL | Buffer | string | PathLike ``` ```typescript Uint8Array | ArrayBuffer | Blob | URL | File | string ``` ```typescript { producer?: string; author?: string; title?: string; creator?: string; } ``` ```typescript string | string[] | number | number[] | undefined | null ``` -------------------------------- ### Merge PDFs in Node.js Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Use the default export from the main entry point to merge local PDF files and save the result to the filesystem. ```javascript import PDFMerger from 'pdf-merger-js'; const merger = new PDFMerger(); await merger.add('./file1.pdf'); await merger.add('./file2.pdf', '1-3'); await merger.save('./output.pdf'); ``` -------------------------------- ### Handle Invalid Page Selection Error Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Triggered when the page selection string format is incorrect. ```bash $ pdf-merge -o output.pdf 'input.pdf#invalid' An error occurred while merging the PDFs: Invalid parameter "pages". Must be a string like "1,2,3" or "1-3" or an Array of numbers. ``` -------------------------------- ### save() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Downloads the merged PDF directly in the browser. ```APIDOC ## save(fileName) ### Description Downloads the merged PDF directly in the browser. Triggers a download dialog and automatically appends .pdf extension. ### Parameters - **fileName** (string) - Required - Base filename without extension. ### Returns - **Promise** ``` -------------------------------- ### Perform Basic Merge Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Combine multiple PDF files into a single document. ```javascript import PDFMerger from 'pdf-merger-js'; const merger = new PDFMerger(); await merger.add('doc1.pdf'); await merger.add('doc2.pdf'); await merger.save('merged.pdf'); ``` -------------------------------- ### Merge PDFs via Node.js Child Process Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Execute the CLI tool programmatically from a Node.js environment using child_process. ```javascript import { execFile } from 'child_process'; import { promisify } from 'util'; const execFileAsync = promisify(execFile); async function mergePDFsViaCLI(inputFiles, outputPath) { try { const { stdout } = await execFileAsync('pdf-merge', [ '--output', outputPath, ...inputFiles ]); console.log(stdout); } catch (error) { console.error('Merge failed:', error.stderr); throw error; } } await mergePDFsViaCLI(['a.pdf#1-3', 'b.pdf#5'], 'output.pdf'); ``` -------------------------------- ### Handle Empty Document Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Catch errors when attempting to save a PDF document that contains no pages. ```javascript const merger = new PDFMerger(); // No pages added try { const buffer = await merger.saveAsBuffer(); // May fail depending on pdf-lib version } catch (error) { console.error('Cannot save empty document'); } ``` -------------------------------- ### Catching Browser Input Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Demonstrates how to catch and identify URL validation errors in the browser. ```javascript try { await merger.add('not a url'); } catch (error) { if (error.message.includes('not a valid url')) { console.error('URL format is invalid'); } } ``` -------------------------------- ### Handle Missing Output Flag Error Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Triggered when the --output flag is omitted during execution. ```bash $ pdf-merge input1.pdf input2.pdf Please provide an output file using the --output flag ``` -------------------------------- ### saveAsBuffer() / saveAsBlob() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Exports the merged PDF as a binary format. ```APIDOC ## saveAsBuffer() / saveAsBlob() ### Description Exports the merged PDF as a binary buffer (Node.js) or a Blob (Browser). ``` -------------------------------- ### Catching Input Type Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Demonstrates how to catch and identify input type errors using the error message string. ```javascript try { await merger.add(someUnknownObject); } catch (error) { if (error.message.includes('pdf-input must be of type')) { console.error('Input type not supported'); } } ``` -------------------------------- ### Parse Single Pages Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Parses a single page number. Whitespace is ignored. ```javascript parsePagesString('2') // [2] parsePagesString(' 2 ') // [2] (whitespace trimmed) ``` -------------------------------- ### add() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Adds pages from a PDF document to the merged output. ```APIDOC ## add(input, pages) ### Description Adds pages from a PDF document to the merged output. Pages are appended to the end of the current document. ### Parameters - **input** (PdfInput) - Required - PDF source: File, Blob, URL string, Uint8Array, ArrayBuffer, or URL object. - **pages** (string | string[] | number | number[] | undefined | null) - Optional - Pages to add. If undefined, adds all pages. 1-indexed. ### Returns - **Promise** ``` -------------------------------- ### Serve PDF via HTTP Response Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Export the merged PDF as a buffer for direct transmission in a Node.js HTTP response. ```javascript import PDFMerger from 'pdf-merger-js'; const merger = new PDFMerger(); await merger.add('doc1.pdf'); await merger.add('doc2.pdf'); const buffer = await merger.saveAsBuffer(); response.setHeader('Content-Type', 'application/pdf'); response.setHeader('Content-Disposition', 'attachment; filename=merged.pdf'); response.end(buffer); ``` -------------------------------- ### Handle PDF Merger Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Use standard try-catch blocks to handle file path errors or invalid page selection parameters. ```javascript try { await merger.add('./missing.pdf'); } catch (error) { if (error.message.includes('neither a valid file-path')) { console.error('File not found or invalid URL'); } else if (error.message.includes('Invalid parameter')) { console.error('Invalid page selection format'); } else { console.error('Unknown error:', error.message); } } ``` -------------------------------- ### Handle File System Write Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Catch specific Node.js file system errors like permission issues or missing directories during the save process. ```javascript try { await merger.save('/read-only-dir/output.pdf'); } catch (error) { if (error.code === 'EACCES') { console.error('Permission denied'); } else if (error.code === 'ENOENT') { console.error('Directory does not exist'); } } ``` -------------------------------- ### Merge Multiple Page Ranges Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Combine non-contiguous pages from several source documents. ```bash pdf-merge -o report.pdf \ 'section1.pdf#1-5' \ 'section2.pdf#3,7,9-11' \ 'appendix.pdf#1-2' ``` -------------------------------- ### Parse Ranges with 'to' Keyword Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Alternative range syntax using the 'to' keyword, which is case-insensitive. ```javascript parsePagesString('1to3') // [1, 2, 3] parsePagesString(' 1to3 ') // [1, 2, 3] parsePagesString(' 1 to 3 ') // [1, 2, 3] parsePagesString('2 to 6') // [2, 3, 4, 5, 6] ``` -------------------------------- ### Merge PDFs via CLI Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Execute the pdf-merge command to combine specific pages from multiple PDF files into a single output file. ```bash pdf-merge --output merged.pdf 'file1.pdf#1-3' 'file2.pdf#5-7' ``` -------------------------------- ### Function Signature Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md The function accepts a string and returns an array of numbers. ```javascript function parsePagesString(pages: string): number[] ``` -------------------------------- ### Clear memory with reset() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md Call reset() on a merger instance to clear memory after saving a document, allowing the instance to be reused for subsequent merges. ```javascript const merger = new PDFMerger(); // Merge 1 await merger.add('file1.pdf'); await merger.save('output1.pdf'); // Clear memory merger.reset(); // Merge 2 await merger.add('file2.pdf'); await merger.save('output2.pdf'); ``` -------------------------------- ### reset() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMergerBase.md Clears the internal PDF document state, allowing the merger instance to be reused. ```APIDOC ## reset() ### Description Clears the internal PDF document state, discarding all accumulated pages and metadata. ### Returns - **void** ``` -------------------------------- ### Detect Global Environment Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/configuration.md Used internally to identify the execution environment, supporting modern environments, browsers, and web workers. ```javascript const globalObject = typeof globalThis === 'object' ? globalThis // Modern environments : typeof window === 'object' ? window // Browser : typeof self === 'object' ? self // Web Worker : this ``` -------------------------------- ### Handle Errors in Browser Context Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Manage errors specifically when working with file inputs and blobs in a browser environment. ```javascript import PDFMerger from 'pdf-merger-js/browser'; const merger = new PDFMerger(); try { const fileInput = document.querySelector('input[type="file"]'); for (const file of fileInput.files) { await merger.add(file); } const blob = await merger.saveAsBlob(); downloadBlob(blob, 'merged.pdf'); } catch (error) { if (error.message.includes('not a valid url')) { console.error('URL error:', error.message); } else { showErrorMessage(error.message); } } ``` -------------------------------- ### PDFMerger.add(pdf, pages) Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/types.md Adds a PDF file to the merger. The pages parameter accepts various formats to specify which pages to include. ```APIDOC ## PDFMerger.add(pdf, pages) ### Description Adds a PDF file to the merger instance. Page numbers are 1-indexed. ### Parameters - **pdf** (string | Buffer | Uint8Array | ArrayBuffer) - Required - The PDF source file. - **pages** (string | string[] | number | number[] | undefined | null) - Optional - Specifies which pages to include. Defaults to all pages if undefined or null. ``` -------------------------------- ### Run in Silent Mode Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Suppresses standard output, useful for automation scripts. ```bash pdf-merge -s -o merged.pdf input1.pdf input2.pdf # No output unless an error occurs ``` -------------------------------- ### Metadata Interface Definition Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMergerBase.md Defines the structure for PDF metadata, where all fields are optional. ```javascript interface Metadata { producer?: string author?: string title?: string creator?: string } ``` -------------------------------- ### Serialize document to Base64 Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMergerBase.md Serializes the internal document to a Base64 data URI, primarily used for browser-based download functionality. ```javascript async _saveAsBase64(): Promise ``` -------------------------------- ### Merge Selective Pages Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Specify page ranges or individual pages to include from source files. ```javascript const merger = new PDFMerger(); await merger.add('file1.pdf', '1-5'); // Pages 1-5 await merger.add('file2.pdf', [3, 7, 9]); // Pages 3, 7, 9 await merger.add('file3.pdf', '1-2,5'); // Pages 1, 2, 5 await merger.save('output.pdf'); ``` -------------------------------- ### Merge with Complex Page Selection Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Merge specific page ranges from multiple files. ```bash pdf-merge -o merged.pdf 'file1.pdf#1-2' 'file2.pdf#1,2,5-7' ``` -------------------------------- ### save() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Node.md Saves the merged PDF to the file system and resets the internal document state. ```APIDOC ## save(fileName) ### Description Saves the merged PDF to the file system and resets the internal document state. The file is written synchronously to the specified path. ### Parameters - **fileName** (string | PathLike) - Required - Output file path. Can be relative or absolute. ### Return Type - **Promise** ``` -------------------------------- ### Convert input to Uint8Array Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMergerBase.md Converts various input formats like Uint8Array, ArrayBuffer, Blob, or URL into a Uint8Array. Subclasses provide additional support for file paths or File objects. ```javascript async _getInputAsUint8Array(input: PdfInput): Promise ``` -------------------------------- ### add(input, pages) Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMergerBase.md Adds pages from a source PDF to the merged document. Supports various page selection formats including single pages, arrays, and ranges. ```APIDOC ## add(input, pages) ### Description Adds pages from a source PDF to the merged document. The method handles page selection parsing and delegates to internal page addition logic. ### Parameters - **input** (PdfInput) - Required - PDF source (type varies by implementation) - **pages** (string | string[] | number | number[] | undefined | null) - Optional - Page selection specification (e.g., 'all', '1-3', [1, 3]) ### Returns - **Promise** ``` -------------------------------- ### Silent Mode for Scripts Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Execute merge without console output, suitable for automated workflows. ```bash pdf-merge -s -o output.pdf input1.pdf input2.pdf if [ $? -eq 0 ]; then echo "Merge successful" else echo "Merge failed" fi ``` -------------------------------- ### Export as Buffer Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Retrieve the merged PDF as a Uint8Array for server uploads or local blob creation. ```javascript import PDFMerger from 'pdf-merger-js/browser'; const merger = new PDFMerger(); const fileInput = document.querySelector('input[type="file"]'); for (const file of fileInput.files) { await merger.add(file); } const buffer = await merger.saveAsBuffer(); // Upload to server const formData = new FormData(); formData.append('pdf', new Blob([buffer], { type: 'application/pdf' })); await fetch('/api/upload', { method: 'POST', body: formData }); // Or create preview blob const blob = new Blob([buffer], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); ``` -------------------------------- ### Catching PDFMerger.add() Validation Errors Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/errors.md Pattern for identifying and handling specific page parameter validation errors. ```javascript try { await merger.add(pdf, 'invalid'); } catch (error) { if (error.message.includes('Invalid parameter "pages"')) { console.error('Page selection format is invalid'); } } ``` -------------------------------- ### save(fileName) Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/README.md Saves or downloads the merged PDF. ```APIDOC ## save(fileName) ### Description Finalizes the merge and saves the result as a file (Node.js) or triggers a browser download. ``` -------------------------------- ### Set PDF Metadata Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Apply custom metadata fields like author or title to the merged document before saving. ```javascript const merger = new PDFMerger(); const fileInput = document.querySelector('input[type="file"]'); for (const file of fileInput.files) { await merger.add(file); } await merger.setMetadata({ producer: 'My PDF Application', author: 'Web User', title: 'Merged Report' }); const blob = await merger.saveAsBlob(); ``` -------------------------------- ### Merge PDFs via Shell Script Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/cli.md Automate PDF merging by invoking the CLI directly from a bash script. ```bash #!/bin/bash INPUT_DIR="./pdfs" OUTPUT_FILE="merged.pdf" # Merge all PDFs in directory, extracting first 5 pages from each pdf-merge -o "$OUTPUT_FILE" \ "$INPUT_DIR/doc1.pdf#1-5" \ "$INPUT_DIR/doc2.pdf#1-5" \ "$INPUT_DIR/doc3.pdf#1-5" if [ $? -eq 0 ]; then echo "✓ Merge complete: $OUTPUT_FILE" else echo "✗ Merge failed" exit 1 fi ``` -------------------------------- ### parsePagesString(pages) Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/parsePagesString.md Parses a string specification of pages into an array of integers. Supports comma-separated values, hyphens, and 'to' keywords for ranges. ```APIDOC ## parsePagesString(pages) ### Description Parses a string input representing page numbers or ranges into an array of integers. The function validates the input string against a specific format before parsing. ### Parameters - **pages** (string) - Required - A string representing pages, such as "1,2,3", "1-3", or "1to3". ### Usage Example ```javascript import { parsePagesString } from 'pdf-merger-js'; const pages = parsePagesString('1,5-7,10'); console.log(pages); // [1, 5, 6, 7, 10] ``` ### Validation Rules - Only positive integers are allowed. - Ranges can be specified using hyphens (-) or the "to" keyword. - Multiple items must be separated by commas (,). - Spaces around numbers and operators are automatically trimmed. - Empty strings, negative numbers, decimals, and special characters will result in an error. ``` -------------------------------- ### reset() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Resets the internal document state, discarding all accumulated pages and metadata. ```APIDOC ## reset() ### Description Resets the internal document state, discarding all accumulated pages and metadata. Allows reuse of the same PDFMerger instance for a new merge operation. ### Signature `reset(): void` ### Returns - **void** ``` -------------------------------- ### Save Merged PDF Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Browser.md Trigger a browser download of the merged PDF. The .pdf extension is automatically appended to the provided filename. ```javascript import PDFMerger from 'pdf-merger-js/browser'; const merger = new PDFMerger(); const files = document.querySelector('input[type="file"]').files; for (const file of files) { await merger.add(file); } // Download with automatic .pdf extension // Prompts user to save as "merged.pdf" await merger.save('merged'); // Resulting file: "merged.pdf" ``` -------------------------------- ### saveAsBuffer() Source: https://github.com/nbesli/pdf-merger-js/blob/master/_autodocs/api-reference/PDFMerger-Node.md Exports the merged PDF as a Node.js Buffer without writing to disk. ```APIDOC ## saveAsBuffer() ### Description Exports the merged PDF as a Node.js Buffer without writing to disk. Useful for streaming, API responses, or further processing. ### Return Type - **Promise** - Node.js Buffer containing the complete PDF binary ```