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

Use a real browser engine when the page depends on JavaScript, fonts, or client-side data. The most practical API patterns are Playwright’s page.pdf(), Chrome DevTools Protocol’s Page.printToPDF, and Puppeteer’s PDF method. Each navigates to a URL (or renders supplied HTML), waits for the page’s actual ready state, applies print settings, and returns PDF bytes.

This guide shows a production-minded Playwright implementation first, then the equivalent CDP and Puppeteer approaches, rendering controls, failure recovery, and when a managed API is preferable to operating Chromium yourself.

Choose the conversion approach

Approach Best fit Important characteristic
Playwright page.pdf() Teams already using Playwright or needing a clear, high-level API Returns a PDF buffer and prints with print CSS by default
Chrome DevTools Protocol Page.printToPDF Services that drive Chromium directly Low-level control over paper, margins, ranges, outlines, tags, and transfer mode
Puppeteer JavaScript services built around Puppeteer Higher-level browser automation with PDF generation
Managed browser/PDF API Teams that do not want to patch, scale, and secure browsers Less infrastructure control; check current limits, retention, compliance, and price

Browser rendering is the dependable option for JavaScript-heavy pages. A simple HTTP fetch only receives the initial HTML; it cannot execute the application code that fills in prices, charts, account data, or lazy-loaded sections.

Convert a URL to PDF with Playwright

Install Playwright and its Chromium browser in your service:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Epson Workforce ES-50 Compact & Lightweight Mobile Document Scanner
  • PORTABLE SCANNER FOR USE ON-THE-GO — The fastest and lightest mobile single-sheet-fed compact document scanner in its class¹
  • QUICK DOCUMENT SCANNING ― This Epson ultra-fast scanner scans a single page as quickly as 5.5 seconds²; Windows and Mac compatible
  • VERSATILE PAPER HANDLING ― Portable scanner scans documents up to 8.5 x 72 in; Also easily digitizes receipts and ID cards to make accounting, bookkeeping, and organizing simpler
  • INTUITIVE, HIGH-SPEED SOFTWARE — Epson ScanSmart Software³ is a smart tool allowing you to easily scan, review, and save; Stay organized easily with the help of this Epson scanner
  • EASY SETUP — USB-powered connect to your computer for quick and simple scanning; No batteries or external power supply required to operate portable document scanner; Standard Connectivity: USB 2.0
npm install playwright
npx playwright install chromium

The following Express-style handler accepts a URL, validates it, waits for a meaningful application signal, waits for fonts and images, and sends the resulting bytes. Replace the allow-list with the destinations your application is permitted to fetch.

import express from 'express';
import { chromium } from 'playwright';

const app = express();
const browser = await chromium.launch();
const allowedHosts = new Set(['example.com', 'www.example.com']);

app.get('/pdf', async (req, res) => {
  let target;
  try {
    target = new URL(String(req.query.url));
    if (target.protocol !== 'https:' || !allowedHosts.has(target.hostname)) {
      return res.status(400).send('URL is not allowed');
    }
  } catch {
    return res.status(400).send('Invalid URL');
  }

  const context = await browser.newContext();
  const page = await context.newPage();
  try {
    await page.goto(target.href, { waitUntil: 'domcontentloaded', timeout: 45000 });
    await page.waitForSelector('[data-pdf-ready="true"]', { timeout: 30000 });
    await page.evaluate(async () => {
      await document.fonts.ready;
      await Promise.all(Array.from(document.images).map(img =>
        img.complete ? Promise.resolve() : new Promise(resolve => {
          img.addEventListener('load', resolve, { once: true });
          img.addEventListener('error', resolve, { once: true });
        })
      ));
    });

    const pdf = await page.pdf({
      format: 'A4',
      printBackground: true,
      margin: { top: '18mm', right: '16mm', bottom: '18mm', left: '16mm' },
      preferCSSPageSize: true,
      tagged: true,
      outline: true
    });
    res.type('application/pdf').send(pdf);
  } catch (error) {
    console.error('PDF conversion failed', { url: target.href, error });
    res.status(502).send('The page could not be rendered');
  } finally {
    await context.close();
  }
});

app.listen(3000);

Use an application-owned readiness marker such as data-pdf-ready="true" rather than assuming a fixed delay means the page is complete. For pages without such a marker, wait for a stable selector and then explicitly wait for fonts and critical images.

Print CSS versus screen CSS

Playwright documents that page.pdf() generates a PDF using print CSS media. If the on-screen design is the required output, call:

await page.emulateMedia({ media: 'screen' });
const pdf = await page.pdf({ printBackground: true });

Keep print media when you have dedicated print rules. Use @media print to remove navigation, adjust typography, and control page breaks. If exact colors matter, -webkit-print-color-adjust: exact can help, but final appearance still depends on browser behavior.

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

Paper, margins, scale, and page breaks

  • Size: choose format: 'A4', 'Letter', or explicit width and height.
  • Margins: set each side explicitly when headers, footers, or tables must not collide with content.
  • Backgrounds: printBackground is false by default; enable it for colored sections, charts, and background images.
  • CSS page size: preferCSSPageSize: true lets the document’s @page rule take precedence.
  • Scale: the documented default is 1; the allowed range is 0.1–2. Lower values fit more content but reduce legibility.
  • Ranges: use pageRanges: '1-3' for partial exports.
  • Navigation and accessibility: outline: true requests a document outline and tagged: true requests tagged output.

For predictable breaks, combine @page with rules such as break-inside: avoid on cards and table rows, and break-before: page on major sections. Test long tables, fixed-position elements, and very wide code blocks at the actual paper size.

Rank #2
Sale
Brother DS-640 Compact Mobile Document Scanner, (Model: DS640)
  • FAST SPEEDS - Scans color and black and white documents a blazing speed up to 16ppm (1). Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • ULTRA COMPACT – At less than 1 foot in length and only about 1. 5lbs in weight you can fit this device virtually anywhere (a bag, a purse, even a pocket).
  • READY WHENEVER YOU ARE – The DS-640 mobile scanner is powered via an included micro USB 3. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan.
  • WORKS YOUR WAY – Use the Brother free iPrint&Scan desktop app for scanning to multiple “Scan-to” destinations like PC, Network, cloud services, Email and OCR. (2) Supports Windows, Mac and Linux and TWAIN/WIA for PC/ICA for Mac/SANE drivers. (3)
  • OPTIMIZE IMAGES AND TEXT – Automatic color detection/adjustment, image rotation (PC only), bleed through prevention/background removal, text enhancement, color drop to enhance scans. Software suite includes document management and OCR software. (4)

Headers and footers

Playwright accepts header and footer templates, but they have deliberate limitations: scripts inside templates are not evaluated, and the page’s styles are not visible inside the template. Inline the styles you need and use the supported substitution classes for page number and date. Reserve enough top and bottom margin so the template does not overlap body content.

Use Chrome DevTools Protocol directly

CDP is useful when your service already owns a Chromium connection or needs streaming transfer. After enabling the Page domain and navigating, call Page.printToPDF with options such as:

const result = await cdp.send('Page.printToPDF', {
  landscape: false,
  paperWidth: 8.27,
  paperHeight: 11.69,
  marginTop: 0.7,
  marginBottom: 0.7,
  marginLeft: 0.6,
  marginRight: 0.6,
  printBackground: true,
  preferCSSPageSize: true,
  displayHeaderFooter: false,
  pageRanges: '1-5',
  generateDocumentOutline: true,
  generateTaggedPDF: true,
  transferMode: 'ReturnAsBase64'
});
const pdfBytes = Buffer.from(result.data, 'base64');

The protocol exposes paper orientation and dimensions, margins, background printing, scaling, CSS page-size preference, page ranges, document outlines, tagged PDFs, and either base64 or stream transfer. A stream mode is preferable when output is large, because it avoids holding the entire encoded document in an intermediate string.

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

Puppeteer alternative

Puppeteer is a JavaScript library for automating Chrome and Firefox through Chrome DevTools Protocol and WebDriver BiDi, and it includes PDF generation. If your existing workers, plugins, and deployment already use Puppeteer, the equivalent flow is:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com/report', {
  waitUntil: 'networkidle0',
  timeout: 45000
});
await page.emulateMediaType('print');
await page.evaluate(() => document.fonts.ready);
const pdf = await page.pdf({
  format: 'A4',
  printBackground: true,
  preferCSSPageSize: true,
  margin: { top: '18mm', right: '16mm', bottom: '18mm', left: '16mm' }
});
await browser.close();
await Bun.write('report.pdf', pdf);

Use an application-specific readiness condition instead of relying solely on networkidle0 when a page maintains analytics, WebSockets, or polling connections.

Rank #3
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
  • STAY ORGANIZED – Easily convert your paper documents into digital formats like searchable PDF files, JPEGs, and more.Power Consumption : 2.5W or less (Energy Saving Mode: 0.7W). Suggested Daily Volume : 500 scans..Does it contain liquid: no
  • CONVENIENT AND PORTABLE –lightweight and small in size, you can take the scanner anywhere from home offices, classrooms, remote offices, and anywhere in between
  • HANDLES VARIOUS MEDIA TYPES – Digitize receipts, business cards, plastic or embossed cards, reports, legal documents, and more
  • FAST AND EFFICIENT – No technical hurdles or complicated setups here; easily scan both sides of a document at the same time, in color or black-and-white, at up to 12 pages-per-minute, and with a 20 sheet automatic feeder
  • BROAD COMPATIBILITY – Works with both Windows and Mac devices, be it laptop or computer

Accept HTML instead of a URL

An HTML-to-PDF API can render a supplied document in a new page:

await page.setContent(html, { waitUntil: 'domcontentloaded' });
await page.evaluate(() => document.fonts.ready);
const pdf = await page.pdf({ format: 'A4', printBackground: true });

Decide whether external images, fonts, and stylesheets are allowed. Sanitize untrusted HTML, limit its size, and isolate the browser context so supplied markup cannot reach internal services or credentials.

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

Production controls: reliability, security, and cost

Navigation and resource controls

  • Validate schemes and hostnames; block private IP ranges and cloud metadata endpoints when users can submit URLs.
  • Set navigation, selector, and overall job timeouts. Abort requests for disallowed resource types or oversized downloads.
  • Keep cookies, authorization headers, and user data in an isolated context. Never log rendered HTML or sensitive query strings by default.
  • Cap concurrency. Each active page consumes CPU, memory, file descriptors, and network bandwidth.

Browser lifecycle

Reuse a browser process, create a fresh context per job, and close every page and context in a finally block. Recycle the browser after a defined number of jobs or when memory grows. In a queue-based service, return a job identifier and store the PDF in object storage rather than keeping large buffers in request memory.

Retries and observability

Retry transient navigation failures with bounded exponential backoff, but do not blindly retry deterministic errors such as an invalid certificate, blocked destination, or a selector that never exists. Record URL hostname, browser version, elapsed phases, final HTTP status, timeout reason, and PDF byte size; omit document contents and credentials. Compare self-hosting with a managed service on rendering fidelity, browser and font control, network access, cold starts, concurrency, data residency, retention, diagnostics, per-document cost, and vendor lock-in. No universal latency, success rate, or market price is established; measure these for your workload.

Or skip the browser setup

ScreenshotNeo is a managed website screenshot API and MCP server. It can also return a PDF from one request, while handling the browser lifecycle for you. Its clean-shot flow accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether it was billed.

For a direct PDF request, see the ScreenshotNeo documentation. The API base is https://api.screenshotneo.com/v1/shot; adapt the target URL as needed:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
  • IRIScan Express, portable scanner : scans color and black and white documents a blazing speed up to 8ppm simplex. Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • IRIScan Express mobile scanner is powered via an included micro USB 2. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan. USB cable provided. AC Adapter not provided and not needed.
  • IRIScan flatbed scanner uses a simplex scanning mode allows for quick and straightforward scanning of single-sided documents. IRIScan with its full portable features is the ideal document scanners for computers.
  • IRIScan document scanner : Versatile scanning capabilities, including scanning to Word, PDF, and Excel formats with companion software provided Readiris OCR
  • Receipt scanner and card scanner with Additional features include scanning business cards directly to Outlook, photo scanning, and receipt scanning for efficient document management
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The same endpoint can be called from Python or Node.js:

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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

It includes PDF controls for paper size, margins, landscape mode, and page ranges, plus full-page rendering, lazy-image loading, custom CSS and JavaScript, selector waits, network-idle waits, headers, cookies, authorization, geolocation, caching, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, and an MCP server with take_screenshot, get_page_info, and capture_pdf tools for AI clients such as Claude and Cursor. Every feature is on every plan: 1,000 shots per month are free with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

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

Troubleshooting common failures

The PDF is blank or missing application data

The capture happened before client-side rendering completed. Wait for a page-owned readiness selector, then fonts and critical images. Increase the navigation timeout only after fixing the readiness signal.

Colors or layout look wrong

Print CSS is active by default. Inspect @media print, choose emulateMedia({ media: 'screen' }) when appropriate, enable printBackground, and verify @page dimensions and margins.

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

Content is clipped or breaks badly

Check paper size, scale, margins, fixed-position elements, and break rules. Use page ranges to isolate a problematic section and test long tables at the target paper format.

Best Value
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
  • Scanner type: Document
  • Connectivity technology: USB
  • With Auto Scan Mode, the scanner automatically detects what you're scanning
  • Digitize documents and images

Background graphics are absent

Enable printBackground: true (or CDP’s equivalent). Ensure the asset request succeeds and that CSS does not hide it in print media.

Headers or footers are unstyled

Template scripts do not run and page styles do not cross into the template. Inline required CSS and reserve margin space.

The export works locally but not in deployment

Confirm that Chromium is installed and compatible, required fonts exist, outbound DNS and HTTPS work, sandbox settings match your container policy, and concurrency has not exhausted memory. The documented Playwright MCP PDF export is Chromium-only.

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

Frequently Asked Questions

Should I use a screenshot endpoint or an HTML-to-PDF endpoint?

Use a PDF-capable browser endpoint when selectable text, pagination, print CSS, outlines, or tagged output matter. A screenshot endpoint is appropriate when a raster image is the intended artifact.

Can I generate only selected pages?

Yes. Playwright and CDP expose page-range controls; pass a range such as 1-3 after the complete document has rendered.

What does a tagged PDF help with?

Tagged output can preserve structural information useful to assistive technology and document navigation, but you should validate the resulting file with your accessibility workflow.

Is a fixed sleep enough for a dynamic page?

No. A selector or application readiness signal is more reliable; also wait for fonts and images that the document needs.

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.

Quick Recap

Bestseller No. 3
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
BROAD COMPATIBILITY – Works with both Windows and Mac devices, be it laptop or computer; This product is not intended for scanning photographs on photo paper / photographic media
$184.00
Bestseller No. 4
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
Find our Software here : irislink.com/start; IRIScan Express is only compatible Windows platform and not macintosh
$129.00
Bestseller No. 5
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Scanner type: Document; Connectivity technology: USB; With Auto Scan Mode, the scanner automatically detects what you're scanning
$75.00

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.