October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Generate a PDF from Multiple HTML Strings with Puppeteer

Build one valid HTML document from your fragments, load it with Puppeteer, and generate a single PDF with the settings your layout needs.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To create one PDF from multiple HTML strings, combine the strings into a single valid HTML document, load it with Puppeteer’s page.setContent(), then call page.pdf(). Puppeteer documents those APIs separately; it does not provide a special multi-fragment PDF method. The assembly step is your code’s responsibility.

Combine the HTML strings into one document

Use one document-level <html>, <head> and <body>. Put the fragments in the body in the order they should appear, and gather shared metadata and styles in the head. This example writes a PDF to disk:

As an Amazon Associate I earn from qualifying purchases.

import puppeteer from 'puppeteer';

const htmlStrings = [
  '<header><h1>Report</h1></header>',
  '<main><p>Report content goes here.</p></main>',
  '<footer><p>End of report</p></footer>'
];

const html = `<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <style>
      body { font-family: sans-serif; }
      @media print {
        .new-page { break-before: page; }
        * { -webkit-print-color-adjust: exact; }
      }
    </style>
  </head>
  <body>${htmlStrings.join('n')}</body>
</html>`;

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.setContent(html);
  await page.pdf({ path: 'output.pdf', format: 'A4', printBackground: true });
} finally {
  await browser.close();
}

The snippets are illustrative; replace them with your actual HTML. page.setContent(html) loads the combined page, and page.pdf(options) renders that page as PDF. See the Puppeteer page.setContent() reference and PDF generation reference.

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

When the strings contain complete documents

Do not concatenate multiple complete <html> documents. Extract or normalize their body content, and deliberately carry over any required stylesheets, scripts, fonts, metadata, and image URLs into the single assembled document. If styles conflict, scope or reconcile them rather than relying on accidental cascade order.

Wait for the content your PDF needs

After setContent(), wait for any application-specific rendering or assets that must be present before printing. For example, if JavaScript populates report data asynchronously, wait for the relevant condition in your application before calling page.pdf(). Puppeteer’s PDF option waitForFonts defaults to true and waits for document.fonts.ready; that does not mean arbitrary application data or every external resource is ready. The API reference notes font readiness may require bringing a background page to the front. See Puppeteer PDF options.

Choose print media, paper size, and appearance

PDF generation uses the print CSS media type by default. If you want the page’s screen styling instead, call await page.emulateMediaType('screen') before generating the PDF. Print rendering can change colors; use -webkit-print-color-adjust: exact when exact color treatment matters, and set printBackground: true if CSS background graphics should be included. Background printing is off by default.

Setting Use Behavior to know
format Choose a named paper format, such as 'A4' or 'Letter'. If provided alongside width or height, format takes priority.
width and height Set explicit paper dimensions when you do not use a named format. CSS @page dimensions take priority only when preferCSSPageSize: true.
preferCSSPageSize Let CSS @page control the paper size. Defaults to false; otherwise the content is scaled to fit the configured paper.
landscape Use landscape orientation for wide content. Defaults to false.
margin Set page margins. Margins are undefined by default; choose them to suit the layout.
pageRanges Print only selected pages. Use when you need a subset of the output.
scale Adjust rendered size. The documented range is 0.1 to 2.
displayHeaderFooter and templates Add page labels or numbering. Templates can use classes such as pageNumber and totalPages.

These options are documented in the Puppeteer PDF options reference. If sections need to begin on new pages, apply print CSS such as break-before: page to their wrappers, then inspect the resulting pagination; a CSS break rule is a layout instruction, not a guarantee that every combination of content will paginate as intended.

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

Choose how to receive the PDF

page.pdf() returns a Promise<Uint8Array>. Supply path to write the PDF to a file; without it, Puppeteer returns the bytes without writing a file. Use page.createPDFStream() when a readable stream suits your application. See the PDF method reference, PDF options, and PDF stream reference.

// Return PDF bytes to the caller
const pdfBytes = await page.pdf({ format: 'A4', printBackground: true });

// Or create a readable stream
const pdfStream = await page.createPDFStream({ format: 'A4' });

Troubleshoot common output problems

  • Only one fragment appears: confirm that all strings are included in the assembled body and that the complete HTML is passed to setContent().
  • Styles disappear or look inconsistent: move required styles into the assembled head or retain the needed linked stylesheets. Check whether print media rules differ from screen rules.
  • Backgrounds or colors are missing: enable printBackground: true for background graphics and use -webkit-print-color-adjust: exact for color fidelity where needed.
  • Fonts or dynamic content are missing: wait for the application’s actual rendering condition before printing. The default font wait only waits for document.fonts.ready, not application data.
  • Paper size is unexpected: check whether format is overriding width/height, and whether preferCSSPageSize should allow CSS @page dimensions to take priority.
  • Page breaks or clipping look wrong: inspect the output with the final content and paper settings; adjust print CSS, margins, orientation, or scale, then render again.

Or skip the browser setup

If you need a screenshot or PDF from a web page rather than a PDF assembled from your own HTML fragments, ScreenshotNeo offers a one-call API. It is not a replacement for composing arbitrary HTML strings into a document with Puppeteer. For a page capture, this cURL example saves a WebP screenshot:

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 API documentation for options and PDF output. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Frequently Asked Questions

Does Puppeteer have a method that accepts an array of HTML strings for one PDF?

No documented multi-string PDF method is described; combine the content into one document and render that page.

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

Does `page.pdf()` use screen styles by default?

No. It uses print media by default; emulate screen media first if that is the appearance you need.

Best Value
The SQL Programming Language: .
  • Used Book in Good Condition

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.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
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.