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.

Convert an HTML template to PDF by rendering it in a browser engine and exporting the page, or by posting the HTML (or template data) to a hosted conversion API. In either case, control print CSS, page dimensions, margins, fonts, backgrounds and asset loading, then test the actual PDF with long tables, images and page breaks before putting it into production.

Choose the conversion architecture

Your first decision is where the browser-quality rendering process runs.

Route How it works Best fit Trade-offs to verify
Self-hosted browser Your application launches Chromium through Puppeteer or Playwright, loads the template, waits for assets and calls the page PDF method. Teams needing local control, custom networking or an existing browser-automation stack. Browser binaries, process limits, sandboxing, memory, scaling and upgrades are your responsibility.
Hosted raw-HTML API Send document markup to an HTTPS endpoint and receive a PDF, download URL or asynchronous job result. Requests where each document is assembled at runtime. Provider-specific authentication, payload limits, retention, timeouts and output handling.
Hosted stored-template API Keep markup with the provider and submit a template identifier plus per-document data. Repeated invoices, reports or certificates with a stable layout. Template versioning, data limits and provider-specific fields.

Official documentation describes these capabilities but does not establish a universal speed, cost or reliability winner. Compare operational ownership, CSS fidelity, job handling and document delivery for your workload.

Self-hosted conversion with Puppeteer

Puppeteer’s page.pdf() renders the current page and creates a PDF. The method uses print CSS by default and waits for fonts to load by default. See the Puppeteer PDF guide, Page.pdf() reference and PDFOptions reference for version-specific options.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Install and create a minimal project

mkdir html-to-pdf
cd html-to-pdf
npm init -y
npm install puppeteer

Puppeteer downloads a compatible browser during installation. In restricted build environments, install the browser separately and configure the executable path according to the version you use.

Complete HTML-template example

The following script reads a template, substitutes escaped values, waits for network activity and writes a PDF. Keep untrusted values escaped; do not concatenate user-provided HTML into a page without sanitizing it.

const fs = require('node:fs/promises');
const puppeteer = require('puppeteer');

function escapeHtml(value) {
  return String(value)
    .replaceAll('&', '&')
    .replaceAll('<', '&lt;')
    .replaceAll('>', '&gt;')
    .replaceAll('"', '&quot;')
    .replaceAll("'", '&#39;');
}

(async () => {
  const template = await fs.readFile('./template.html', 'utf8');
  const html = template
    .replace('{{name}}', escapeHtml('Ada Lovelace'))
    .replace('{{date}}', escapeHtml(new Date().toISOString().slice(0, 10)));

  const browser = await puppeteer.launch({headless: true});
  try {
    const page = await browser.newPage();
    await page.setContent(html, {waitUntil: 'networkidle0'});
    await page.emulateMediaType('print');
    await page.pdf({
      path: './output.pdf',
      format: 'A4',
      printBackground: true,
      preferCSSPageSize: true,
      margin: {top: '18mm', right: '16mm', bottom: '18mm', left: '16mm'},
      displayHeaderFooter: false
    });
  } finally {
    await browser.close();
  }
})();

Create template.html with normal HTML and print rules:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    @page { size: A4; margin: 18mm 16mm; }
    body { font-family: Arial, sans-serif; color: #1f2937; }
    h1 { break-after: avoid; }
    table { width: 100%; border-collapse: collapse; }
    tr { break-inside: avoid; }
    th, td { border: 1px solid #d1d5db; padding: 6pt; }
    .page-break { break-before: page; }
    * { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
  </style>
</head>
<body>
  <h1>Invoice for {{name}}</h1>
  <p>Issued: {{date}}</p>
</body>
</html>

Print CSS versus screen CSS

Both Puppeteer and Playwright document print media as the default for PDF generation. If your template is designed for a monitor, call page.emulateMediaType('screen') before exporting, then verify the result. Print layouts often need explicit widths, hidden navigation, page-break rules and simplified interactive controls.

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

Set printBackground: true when colored panels or backgrounds matter. Chromium may modify colors for printing; -webkit-print-color-adjust: exact requests closer color preservation, but always inspect the generated file on your target PDF viewer.

Important PDF options

  • Paper: use format such as A4 or Letter, or explicit width and height with units.
  • Margins: reserve space for printers, headers and footers; CSS @page and API margins can interact, so choose one clear source of truth.
  • CSS page size: preferCSSPageSize lets @page control dimensions when supported by your engine.
  • Headers and footers: Puppeteer and Playwright expose templates. Playwright notes that scripts in header/footer templates do not execute and page styles are not visible inside them.
  • Backgrounds and colors: enable background printing and test transparency or dark themes separately.

Option names and defaults can change with browser-library versions; consult the current references before pinning behavior.

Playwright alternative

Playwright exposes the same basic flow through page.pdf() and supports standard paper formats or dimensions with units. A minimal version is:

const { chromium } = require('playwright');
const browser = await chromium.launch();
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle' });
await page.emulateMedia({ media: 'print' });
await page.pdf({ path: 'output.pdf', format: 'A4', printBackground: true });
await browser.close();

Follow the Playwright Page API for the installed release’s exact options.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Hosted HTML-to-PDF APIs

Raw HTML requests

PDF.co documents POST /pdf/convert/from/html for HTML input. Its asynchronous mode returns a job identifier for long processes; the documentation also describes a default output-link expiration of 60 minutes, with maximum duration depending on subscription plan. Confirm current limits before relying on those values: PDF.co HTML-to-PDF API.

Stored templates and data

PDF.co’s template endpoint accepts a template ID, template data, page settings and an optional callback for asynchronous jobs. The documentation states a request-size limit of less than 4 MB; verify current endpoint behavior and account limits at the template reference.

Rank #3
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Document content or a URL

DocRaptor documents a JSON POST /docs with type: "pdf" and document_content; a URL can also be supplied. Synchronous calls can return PDF bytes, while asynchronous or hosted-document modes change response handling. See DocRaptor’s API overview and API reference.

Reusable, raw HTML, URL and Markdown paths

APITemplate.io documents separate reusable-template and raw-HTML endpoints, plus URL and Markdown methods. Asynchronous calls return a transaction reference and can notify your webhook: overview and generation methods.

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

Keep API keys on your server. Treat vendor payload fields as provider-specific rather than interchangeable, and use placeholders instead of credentials in source code.

Make templates render predictably

  • Wait for assets: use networkidle or an explicit readiness selector, and ensure images and web fonts are reachable from the rendering environment.
  • Embed or host fonts deliberately: missing fonts change line wrapping and pagination. Use stable font files and wait for document.fonts.ready when your engine does not already wait.
  • Control page breaks: use break-before, break-after and break-inside; avoid splitting table rows where possible.
  • Handle external resources: authenticated URLs, blocked third-party requests and relative paths often produce blank images. Use absolute URLs or inject assets, and configure request headers or cookies where your renderer supports them.
  • Separate screen and print components: hide menus, buttons and chat widgets in @media print; provide print-only labels when context would otherwise be lost.

Asynchronous jobs, delivery and retention

Long documents, remote assets and high concurrency make an immediate binary response unreliable as an interface. An asynchronous design returns a job or transaction ID, lets a worker poll status or receive a callback, then retrieves the PDF and stores it under your retention policy. Handle completion, failure, timeout and duplicate callbacks idempotently. Do not assume a hosted download URL is permanent; providers document expiration and retention settings that vary by plan and mode.

Testing and production checklist

  1. Render a short document, a multi-page document and a document with a long table.
  2. Test missing images, slow fonts, SVGs, transparent backgrounds and authenticated assets.
  3. Compare screen and print media intentionally, including colors and links.
  4. Check page numbering, headers, footers, margins, clipping and widows/orphans in a real PDF viewer.
  5. Record renderer and browser versions so a future upgrade can be compared against a known-good PDF.
  6. Load-test browser concurrency or provider quotas without exposing customer data.
  7. Validate the PDF file, page count and expected text before marking a job successful.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common failures

Blank or partially rendered pages

Usually an asset, script or authentication request failed. Log browser console and request failures, use absolute URLs, provide cookies or headers, and wait for a selector that proves the template is ready.

Fonts or line breaks differ

The font was unavailable, still loading or substituted. Package the font, verify its response status and wait for font readiness before calling the PDF method.

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

Colors disappear

Print backgrounds are disabled or print color adjustment changed the palette. Enable background printing and add the print-adjust rule, then verify on the target viewer.

Tables split badly

Apply break-inside: avoid to rows or groups, repeat table headers with print CSS where supported, and redesign rows that cannot fit on one page.

Timeouts or killed browser processes

Reduce concurrent pages, close every browser in a finally block, set explicit navigation and job timeouts, and move long work to a queue. For hosted APIs, use their documented asynchronous mode instead of extending a synchronous request indefinitely.

Hosted API returns a job but no file

Persist the job identifier, poll the documented status endpoint or validate webhook delivery, authenticate the retrieval request and account for link expiration. Treat failed status as a terminal state and record the provider error.

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

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server that can return a clean screenshot or PDF from a URL. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; 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 result in headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.

For a URL that already renders your template, the documented request shape is:

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

Use the ScreenshotNeo documentation for the current PDF output parameter and response handling. The service also supports full-page capture with lazy images loaded, CSS-selector element capture, custom JavaScript and CSS, waiting for a selector, delay or network idle, custom headers and cookies, device and viewport controls, geolocation and timezone, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, caching with a chosen TTL and a usage API.

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account.

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

Which route should you use?

  • Choose Puppeteer or Playwright when you need complete control over browser networking, local data and deployment.
  • Choose a hosted raw-HTML API when you want to avoid browser lifecycle management and each request contains its own markup.
  • Choose a stored-template API when many documents share one layout and only data changes.
  • Choose an asynchronous workflow when rendering can exceed request timeouts or when webhooks and durable storage fit your system better.

Frequently Asked Questions

Does HTML-to-PDF conversion execute JavaScript?

Browser-based renderers execute page JavaScript subject to navigation, resource and sandbox settings. Hosted providers differ, so confirm script support and wait conditions in the provider’s current documentation.

Can I use a URL instead of sending HTML?

Yes. DocRaptor documents URL input, and APITemplate.io documents URL-based generation. A URL must be reachable from the rendering environment and may require authentication or stable asset URLs.

How do I protect private template data?

Keep API keys server-side, avoid putting secrets in client-side HTML, use authenticated asset requests only where supported, and define how long generated PDFs and temporary provider links may be retained.

Why does the same template paginate differently after an upgrade?

Browser and library versions can change font metrics, CSS support and pagination. Pin versions, retain representative PDFs and compare output during upgrades.

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

Quick Recap

SaleBestseller No. 1
HTML and CSS: Design and Build Websites
HTML and CSS: Design and Build Websites
HTML CSS Design and Build Web Sites; Comes with secure packaging; It can be a gift option
$14.94
SaleBestseller No. 3
Web Design with HTML, CSS, JavaScript and jQuery Set
Web Design with HTML, CSS, JavaScript and jQuery Set
Brand: Wiley; Set of 2 Volumes
$35.05

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.