October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
JavaScript

How to Merge Multiple Puppeteer PDF Buffers into One PDF

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use pdf-lib to copy pages from each Puppeteer PDF into a new document. Puppeteer’s page.pdf() returns a Promise<Uint8Array>; load each byte array with PDFDocument.load(), copy its pages with copyPages(), append them to a destination document, and call save() to obtain the merged PDF bytes. Do not concatenate the buffers directly: a PDF is a structured document, not a sequence of independent files.

Install the libraries

This workflow uses Puppeteer for rendering and pdf-lib for document-level page copying. Install them in your Node.js project:

npm install puppeteer pdf-lib

The Puppeteer API page cited here is labeled version 25.12.0. Your lockfile determines the version actually used, so check the installed package documentation when upgrading. The pdf-lib API reference does not establish a single package version.

The complete in-memory merge function

The function below accepts an array of PDF byte arrays and returns one Uint8Array. Pages are appended in input order: every page from the first buffer, then every page from the second, and so on.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
  • COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
  • ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
  • HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
import { PDFDocument } from 'pdf-lib';

export async function mergePdfBuffers(pdfBuffers) {
  if (!Array.isArray(pdfBuffers)) {
    throw new TypeError('pdfBuffers must be an array');
  }

  const mergedPdf = await PDFDocument.create();

  for (const pdfBuffer of pdfBuffers) {
    const sourcePdf = await PDFDocument.load(pdfBuffer);
    const copiedPages = await mergedPdf.copyPages(
      sourcePdf,
      sourcePdf.getPageIndices(),
    );

    for (const page of copiedPages) {
      mergedPdf.addPage(page);
    }
  }

  return mergedPdf.save();
}

PDFDocument.load() accepts PDF bytes such as a Uint8Array, ArrayBuffer, or base64 input, and save() serializes the destination document as a Uint8Array according to the pdf-lib API reference. In Node.js, a Buffer extends Uint8Array, so a Buffer returned by an integration can be passed directly.

Generate the source PDFs with Puppeteer

page.pdf() renders the current page and resolves to PDF bytes. Puppeteer uses print CSS media by default. If your page is styled primarily for screens, call page.emulateMediaType('screen') before generating the PDF. Puppeteer also waits for fonts to load by default, which helps avoid capturing before web fonts are available.

import puppeteer from 'puppeteer';
import { mergePdfBuffers } from './merge-pdf-buffers.js';
import { writeFile } from 'node:fs/promises';

const browser = await puppeteer.launch();

try {
  const page = await browser.newPage();
  await page.goto('https://example.com/report/part-1', {
    waitUntil: 'networkidle0',
  });
  const firstPdf = await page.pdf({
    format: 'A4',
    printBackground: true,
  });

  await page.goto('https://example.com/report/part-2', {
    waitUntil: 'networkidle0',
  });
  const secondPdf = await page.pdf({
    format: 'A4',
    printBackground: true,
  });

  const mergedPdf = await mergePdfBuffers([firstPdf, secondPdf]);
  await writeFile('report.pdf', mergedPdf);
} finally {
  await browser.close();
}

For separate pages, you can create a new page for each URL or reuse one page with another goto(). Keep the resulting byte arrays until the merge completes. The output of writeFile() is a normal Node.js file operation; an HTTP framework can instead send the returned bytes as its response body.

Control page order and select individual pages

Reorder whole documents

Because the outer loop determines append order, reorder the input array when a different sequence is required:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const merged = await mergePdfBuffers([
  appendixPdf,
  coverPdf,
  mainReportPdf,
]);

This produces the appendix first, followed by the cover and main report. No sorting occurs automatically, so make the order explicit in the code that collects the buffers.

Copy selected pages

copyPages(sourcePdf, indices) accepts the source document and an array of zero-based page indices. Use it when you need only selected pages or want to interleave pages from several sources:

Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
  • INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
  • PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
  • ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴
import { PDFDocument } from 'pdf-lib';

export async function mergeSelectedPages(parts) {
  const destination = await PDFDocument.create();

  for (const part of parts) {
    const source = await PDFDocument.load(part.bytes);
    const pages = await destination.copyPages(source, part.pageIndices);
    for (const page of pages) destination.addPage(page);
  }

  return destination.save();
}

const output = await mergeSelectedPages([
  { bytes: coverPdf, pageIndices: [0] },
  { bytes: chapterPdf, pageIndices: [0, 1, 2] },
  { bytes: appendixPdf, pageIndices: [1, 3] },
]);

Indices must refer to pages that exist in the corresponding source. Validate them before calling the API if page selections come from user input.

Return the merged bytes from an HTTP endpoint

In a Node.js server, set a PDF content type and send the byte array using the response API provided by your framework. With a native HTTP server:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import http from 'node:http';

http.createServer(async (_request, response) => {
  try {
    const bytes = await mergePdfBuffers([firstPdf, secondPdf]);
    response.writeHead(200, {
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment; filename="merged.pdf"',
      'Content-Length': bytes.byteLength,
    });
    response.end(Buffer.from(bytes));
  } catch (error) {
    response.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
    response.end('PDF merge failed');
  }
}).listen(3000);

Convert the returned Uint8Array to a Node Buffer only at the boundary where your framework expects one. The merge itself can remain entirely in memory.

Validate inputs before loading

An empty array, malformed PDF, or encrypted file should be treated as an input error. The cited API material does not establish a compatibility guarantee for every malformed or encrypted document, so do not assume all PDFs can be loaded and copied.

function assertPdfBytes(value, index) {
  if (!(value instanceof Uint8Array) && !(value instanceof ArrayBuffer)) {
    throw new TypeError(`PDF ${index} is not a byte array`);
  }
}

export async function safeMerge(pdfBuffers) {
  if (pdfBuffers.length === 0) {
    throw new Error('At least one PDF is required');
  }
  pdfBuffers.forEach(assertPdfBytes);
  return mergePdfBuffers(pdfBuffers);
}

For a stricter application, inspect the first bytes for the conventional %PDF- signature, enforce a maximum input size, and catch the load error so a bad upload does not terminate the process. Signature checking is only an early filter; it does not prove that a file is structurally valid.

What this merge preserves—and what it may not

Page content and order

The documented operation creates a new destination document and copies source pages into it. The order in which pages are added becomes the order in the merged file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
  • INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
  • KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
  • PREMIUM SUPPORT - Strong technical expertise to solve issues faster
  • THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.

Interactive features and signatures

This page-copy workflow should not be advertised as preserving every specialized PDF feature. The cited pdf-lib API material does not establish behavior for digital signatures, all interactive form states, annotations, encryption, or other advanced document features. If those features matter, test the exact files and installed pdf-lib release, and verify the resulting document with the consumer that will open it.

Different page sizes

Each copied page retains its own page dimensions. A merged file can therefore contain mixed sizes and orientations. If a downstream printer or viewer requires a uniform format, normalize page sizes as a separate, deliberate transformation rather than assuming the merge will do it.

Memory, timing, and reliability considerations

In-memory cost

At merge time, the source byte arrays, loaded source documents, copied pages, and serialized output can all be live. Large reports or many parts can therefore consume substantially more memory than the sum of the final file sizes. Limit the number and size of concurrent PDF generations, close the browser in a finally block, and process jobs in bounded batches when necessary.

Generation versus merge failures

A navigation timeout or rendering failure occurs before pdf-lib is involved. Keep generation and merge errors distinguishable in logs so you know whether to retry the web page or reject a malformed PDF. Puppeteer’s default font wait and print-media behavior affect generation timing and appearance, not the page-copy algorithm.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Performance expectations

The supplied API references provide no quantitative benchmark for Puppeteer generation or pdf-lib merging. Measure with your own page sizes, fonts, images, and concurrency rather than publishing a universal throughput figure.

Troubleshoot common failures

Symptom Likely cause Fix
PDFDocument.load rejects the input The bytes are truncated, not a PDF, encrypted, or otherwise unsupported. Confirm the generation call completed, check the byte type and size, save the individual buffer for inspection, and test that exact file with the installed pdf-lib version.
The output contains pages in the wrong order The input array or selected indices are in an unintended order. Log each part’s name and page indices, then reorder the array or the copyPages() index list.
The output is blank or styled unexpectedly Puppeteer rendered print CSS, or navigation finished before page content was ready. Use page.emulateMediaType('screen') when appropriate, choose a suitable waitUntil, and wait for a page-specific selector before calling page.pdf().
Fonts differ between source PDFs Fonts were unavailable at capture time or the pages intentionally use different font resources. Ensure the page reaches its ready state; Puppeteer documents waiting for fonts by default. Check the individual PDFs before merging.
Process memory rises during large jobs All source documents and the destination are retained while serialization occurs. Reduce concurrency, split very large jobs, enforce size limits, and let references go out of scope after each completed job.
HTTP clients receive a corrupt download Text encoding or a framework response helper altered binary data. Send the bytes as binary, use application/pdf, and set Content-Length from byteLength where supported.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your real requirement is a screenshot or PDF of a URL rather than custom Puppeteer code, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—work with Claude, Cursor, and other MCP clients.

For a single URL, the API call is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for output and option details. The equivalent Python request is:

Rank #4
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
  • No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
  • Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
  • Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
  • The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

And in Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also supports full-page capture, element selection, device presets, custom CSS and JavaScript, waits, request blocking, headers and cookies, PDFs with paper and page-range controls, caching, signed links, asynchronous jobs, bulk capture of up to 100 URLs per call, and a usage API. Every feature is on every plan. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Can I merge the raw Puppeteer buffers with Buffer.concat()?

No. Concatenation produces multiple PDF byte streams, not one valid document structure. Load and copy pages into a destination PDF instead.

Do I need to write temporary files?

No. Puppeteer output, pdf-lib input, and pdf-lib output can all stay in memory. Files are needed only if your application chooses to persist or inspect them.

Are page indices zero-based?

Yes. The indices passed to copyPages() identify pages by zero-based position, so the first page is index 0.

Frequently Asked Questions

Can I merge the raw Puppeteer buffers with Buffer.concat()?

No. Concatenation does not create one valid PDF; load each buffer and copy its pages into a destination document.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do I need temporary files?

No. The complete workflow can remain in memory; write files only when persistence or inspection is required.

Quick Recap

Are copyPages indices zero-based?

Yes. The first page is index 0.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.