pdf-merger-js

repository·master·Indexed 43 days ago

https://github.com/nbesli/pdf-merger-js

A lightweight JavaScript library for merging multiple PDF documents or specific page ranges into a single PDF. Version 5.1.2 supports Node.js, the browser, and a CLI tool. It provides the PDFMerger class for programmatic merging and a pdf-merge command for terminal use, with no non-JavaScript dependencies.

Tokens
2.4K
Snippets
9
Records
11
Agent score
54%

What's inside pdf-merger-js

  1. Legacy Version Compatibility

    master

    If you are working with older projects or specific requirements, note the following versioning changes:

    • PDF.js dependency: If you need the legacy version that uses pdfjs, install a v3 release.
    • CommonJS (require) support: If you need to use require() instead of ESM import, install a v4 release.

    Starting from v4, the library uses pdf-lib instead of pdfjs, and starting from v5, it uses modern ESM modules.

  2. Install pdf-merger-js

    master

    You can install the library as a dependency for your project or globally if you only intend to use the CLI tool.

    Project dependency:

    npm install --save pdf-merger-js

    Global installation (for CLI use):

    npm install -g pdf-merger-js
  3. Supported PDF input types

    master

    When adding files to the merger, the input can be one of the following:

    • Buffer
    • string (treated as a local file path if it exists, otherwise treated as a URL)
    • PathLike (Node.js filesystem path type)

    If a string is provided and it is not a valid local file path, the library attempts to treat it as a valid URL. If it is neither, an error is thrown.

  4. Use PDFMerger in Node.js

    master

    In a Node.js environment, use the PDFMerger class to programmatically merge files. The library uses ESM (import) syntax.

    Available Methods:

    • add(pathOrFile, [pages]): Adds a PDF file or part of it. pages can be a single page number, an array of numbers, a comma-separated string, or a range string (e.g., '3-5' or '3 to 5').
    • save(filename): Saves the merged PDF to the specified filename and resets the internal state.
    • saveAsBuffer(): Exports the merged PDF as a Node.js Buffer.
    • setMetadata(metadata): Sets metadata for producer, author, title, or creator.
    • reset(): Resets the internal state to start a new document.

    Example:

    import PDFMerger from 'pdf-merger-js';
    
    var merger = new PDFMerger();
    
    (async () => {
      await merger.add('pdf1.pdf');  // merge all pages
      await merger.add('pdf2.pdf', 2); // merge only page 2
      await merger.add('pdf2.pdf', [1, 3]); // merge pages 1 and 3
      await merger.add('pdf2.pdf', '4, 7, 8'); // merge pages 4, 7 and 8
      await merger.add('pdf3.pdf', '3 to 5'); // merge pages 3 to 5
      await merger.add('pdf3.pdf', '3-5'); // merge pages 3 to 5
    
      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');
    })();
  5. Use PDFMerger in the Browser

    master

    For browser-based applications (like React), import from the /browser entry point. This version is optimized for web environments and handles files as Blobs or File objects.

    Available Methods:

    • add(file): Adds a PDF File or Blob object.
    • saveAsBlob(): Exports the merged PDF as a Blob.
    • saveAsBuffer(): Exports the merged PDF as a Uint8Array.
    • save(): Triggers a file download directly in the browser.
    • setMetadata(metadata): Sets metadata for producer, author, title, or creator.
    • reset(): Resets the internal state.

    Example (React Component):

    import PDFMerger from 'pdf-merger-js/browser';
    import React, { useEffect, useState } from 'react';
    
    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);
    
          setMergedPdfUrl(url);
        };
    
        render().catch((err) => {
          console.error(err);
        });
      }, [files]);
    
      return !mergedPdfUrl ? (
        <>{'Loading...'}</>
      ) : (
        <iframe
          height='1000'
          src={mergedPdfUrl}
          title='pdf-viewer'
          width='100%'
        ></iframe>
      );
    };
  6. Use the pdf-merge CLI

    master

    The pdf-merge command allows you to merge multiple PDF documents or specific page ranges from them via the terminal. You can specify input files and use a # suffix to define page ranges.

    Command Syntax: pdf-merge [options] <inputFiles...>

    Options:

    • -V, --version: Output the version number.
    • -o, --output <outputFile>: Path for the merged PDF output file.
    • -v, --verbose: Print verbose output.
    • -s, --silent: Do not print any output to stdout (overwrites --verbose).
    • -h, --help: Display help for the command.

    Examples:

    Merge pages 1-2 from the first input with pages 1, 2, and 5-7 from the second PDF:

    pdf-merge --output ./merged.pdf ./input1.pdf#1-2 ./input2.pdf#1,2,5-7

    Merge files from URLs (merging a local file with specific pages from a remote URL):

    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
  7. Use the PDFMerger class to merge PDFs

    master

    The PDFMerger class is the primary interface for merging PDF documents. It supports various input types including Buffer, string (representing either a local file path or a URL), and PathLike.

    After adding your PDF inputs, you can export the result using saveAsBuffer() to get a Node.js Buffer or save(fileName) to write the merged file directly to the filesystem.

    import PDFMerger from 'pdf-merger-js';
    
    const merger = new PDFMerger();
    await merger.add(pathOrBufferOrUrl);
    await merger.save('merged.pdf');
  8. Reference the pdf-merge CLI options and arguments

    master

    The following options and arguments are available for the pdf-merge command:

    Arguments

    • <inputFiles...>: One or more paths to the PDF files you want to merge. You can optionally append #<pages> to a file path to specify a subset of pages (e.g., input.pdf#1-5).

    Options

    • -o, --output <outputFile>: Required. The path where the merged PDF output file will be saved.
    • -v, --verbose: Enables verbose output, printing details about which pages are being added from which files.
    • -s, --silent: Suppresses all output to stdout. This flag overrides --verbose.
    pdf-merge <inputFiles...>
      -o, --output <outputFile>   Merged PDF output file path
      -v, --verbose              Print verbose output
      -s, --silent               do not print any output to stdout. Overwrites --verbose
  9. Use the pdf-merge CLI to merge PDF files

    master

    The pdf-merge command allows you to merge multiple PDF files into a single output file from your terminal. You can specify specific pages to include from each input file using a # delimiter followed by a page range string (e.g., file.pdf#1-3).

    Basic Usage: pdf-merge <inputFiles...> --output <outputFile>

    Example:

    # Merge all pages from two files into 'merged.pdf'
    pdf-merge file1.pdf file2.pdf --output merged.pdf
    
    # Merge only pages 1 and 3 from file1.pdf, and all pages from file2.pdf
    pdf-merge file1.pdf#1,3 file2.pdf --output merged.pdf
    pdf-merge file1.pdf file2.pdf --output merged.pdf
  10. Save the merged PDF as a Buffer

    master

    The saveAsBuffer() method asynchronously returns the merged PDF content as a Node.js Buffer. This is useful when you want to process the PDF in memory without writing it to disk immediately.

    const buffer = await merger.saveAsBuffer();