Tutorial

How to Generate PDFs from Web Pages via API

Convert a URL to an A4 PDF with one POST request. The request fields that matter for PDFs, what the API fixes for you, wait strategies, fonts, private pages, and errors.

Asad AliNovember 5, 202411 min read

Screenshotly turns a public URL into an A4 PDF with one HTTP request. Chromium loads the page, applies your print stylesheet and returns the file as application/pdf. This guide covers the API side: the request, the response, and the few settings that change PDF output.

It's the first of four PDF guides. The others cover:

For a summary of the feature and plans, see the URL to PDF API page.

Fixed settings and what you control

The PDF settings are fixed in the renderer. You can't pass them in the request, and the request schema rejects unknown fields such as pdfOptions, landscape or margin.

Setting Value Can you change it?
Paper size A4 (210 × 297 mm) No API field. Named or custom @page sizes in your CSS are ignored
Margins 1 cm on all sides No API field. An @page { margin } rule in your CSS took precedence in our tests
Background graphics Printed Always on
CSS media type print Always print, so @media print rules apply
Headers and footers None added by the API Use CSS margin boxes or repeating table headers in your page
Input A public http/https URL, up to 2,048 characters No raw HTML input

The API doesn't offer Letter, Legal or custom paper sizes, orientation switches, header/footer templates, page ranges, PDF/A, encryption or password protection. If you need any of these, post-process the file with a PDF library, or choose a tool built around them.

PDF output requires the Basic plan or higher. See pricing.

Make your first PDF request

Authenticate with x-api-key (or Authorization: Bearer), send JSON, and write the response body to disk.

curl -X POST https://screenshotly.app/api/screenshot \
  -H "x-api-key: $SCREENSHOTLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com", "format": "pdf"}' \
  --fail --output example.pdf

The same request in Node.js 18+:

import { writeFile } from 'node:fs/promises';

const response = await fetch('https://screenshotly.app/api/screenshot', {
  method: 'POST',
  headers: {
    'x-api-key': process.env.SCREENSHOTLY_API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    url: 'https://example.com',
    format: 'pdf',
  }),
});

if (!response.ok) {
  const error = await response.json();
  throw new Error(`${response.status} ${error.error}: ${error.message ?? ''}`);
}

await writeFile('example.pdf', Buffer.from(await response.arrayBuffer()));

And in Python with requests:

import os
import requests

response = requests.post(
    "https://screenshotly.app/api/screenshot",
    headers={"x-api-key": os.environ["SCREENSHOTLY_API_KEY"]},
    json={"url": "https://example.com", "format": "pdf"},
    timeout=60,
)
response.raise_for_status()

with open("example.pdf", "wb") as f:
    f.write(response.content)

A successful response is 200 with Content-Type: application/pdf, a Content-Disposition: attachment filename, and the X-Screenshot-Duration and X-Screenshot-Size headers. Quota headers (X-RateLimit-Limit, X-RateLimit-Remaining) are included when available.

Request fields for PDFs

All capture fields are accepted with format: "pdf", but only some of them change the result.

Fields that change the PDF

  • waitForNetworkIdle: navigate with Chromium's network-idle wait instead of stopping at DOMContentLoaded. Use it for pages that fetch data or images after load.
  • waitForSelector: wait up to 10 seconds for an element. If it never appears, the capture continues anyway rather than failing, so don't use it as a correctness check.
  • delay: an extra 0–10,000 ms pause before printing, for animations or charts that draw after their data arrives.
  • fullPage: send true for PDFs that use web fonts (see below). The PDF contains the whole document either way.
  • headers and cookies: reach pages behind a session or a token. Both are available on Basic and above.
  • blockAds: blocks requests to known ad hosts and hides common ad and cookie-consent containers.
  • hideSelectors (Growth and above): hide elements by CSS selector without changing your page.
  • darkMode, timezone and userAgent: emulation settings, applied before the page is printed.
  • device, width and height: set the browser viewport. This changes what scripts see in window.innerWidth, but CSS media queries in print are evaluated against the paper, not the viewport (see below).

Fields the PDF ignores

selector, clip, quality and mockup only apply to image formats. The PDF is always the whole document. mockup still needs a Growth plan, so leave it out.

Wait for the page to be ready

By default, the renderer starts printing once the HTML has been parsed. That's fast, but data loaded by client-side JavaScript or late-loading images can be missing from the PDF. Pick the lightest wait that works:

{
  "url": "https://app.example.com/reports/2026-10/print",
  "format": "pdf",
  "fullPage": true,
  "waitForNetworkIdle": true,
  "waitForSelector": "[data-report-ready]",
  "delay": 500
}

One approach: have your print route add a data-report-ready attribute after the last chart has rendered.

Two things don't fail the request: a missing selector, and the HTTP status of your page. If your print route returns a 404 or 500 error page, that page is printed and returned as a normal PDF. So check that the document's data exists before you call the API, and don't treat a 200 from Screenshotly as proof that the document is complete.

The synchronous endpoint allows 30 seconds for navigation. For slow reports, use the async jobs API described in the batch guide.

Load web fonts

To keep viewport screenshots fast, the renderer skips web-font downloads unless fullPage is true. With fullPage omitted, a PDF falls back to the next font in your font-family stack. We confirmed this by rendering the same test page both ways: without fullPage, the PDF embedded the fallback font; with fullPage: true, it embedded the web font.

For PDFs, either:

  • send fullPage: true whenever your page loads fonts with @font-face, or
  • use a system font stack in your print CSS so nothing needs downloading.

Capture private pages

The renderer can only load addresses on the public internet. Requests for localhost, private IP ranges and internal hostnames are rejected with 400 Unsafe URL. For pages behind a login, pass credentials with the request:

{
  "url": "https://app.example.com/invoices/inv_8f2c/print",
  "format": "pdf",
  "fullPage": true,
  "headers": { "Authorization": "Bearer <short-lived token for this document>" },
  "cookies": [{ "name": "session", "value": "<session value>", "secure": true, "httpOnly": true }]
}

Requests can include up to 50 headers and 50 cookies. Each cookie's domain must match the target URL's host. Use a token that is scoped to the one document and expires quickly, rather than a long-lived admin session. The invoice guide shows the full pattern.

Add "storage": { "enabled": true } (Basic and above) and the API returns JSON instead of the binary:

{
  "success": true,
  "url": "https://screenshotly.app/api/assets/…?expires=…&signature=…",
  "format": "pdf",
  "size": 48213,
  "duration": 2140
}

The URL is signed and expires. Download the file and store it yourself if you need to keep it longer than your account's retention setting (1–30 days).

Handle errors

Status Meaning for PDF requests
400 Invalid JSON, an unknown field (for example pdfOptions), an unsafe URL, or a bad cookie domain
401 Missing, invalid, expired or revoked API key
403 Your plan doesn't include a requested feature. The body names it and includes minimumPlan
413 Request body larger than 64 KiB
429 Monthly quota or per-minute limit reached; respect Retry-After
500 The page couldn't be rendered (for example, a navigation timeout)
503 A requested optional adapter, such as a regional proxy, isn't configured

Failed captures don't count against your monthly quota.

How PDF output differs from the screen

Chromium prints with your print CSS, not your screen CSS. Most problems that look like rendering bugs are actually print-layout behavior:

  • Breakpoints follow the paper. The printable area of A4 with 1 cm margins is 190 mm, about 718 CSS pixels. A min-width: 900px media query is false in the PDF even with a 1920 px viewport. JavaScript that measures window.innerWidth still sees the viewport, so size charts in CSS rather than from the window width.
  • Fixed elements repeat. A position: fixed navigation bar appears on every page. Hide it with @media print.
  • Colors can shift. Chromium may adjust colors for printing unless you set print-color-adjust: exact.
  • Animations freeze at whatever frame they're on when printing starts.

The CSS print styling guide covers each of these with tested CSS.

Sample output

Two A4 pages of a sample invoice PDF. Page 1 shows the seller, customer and the first 16 line items. Page 2 repeats the table header, lists the remaining items and the totals. Each page has a "Page N of 2" footer.

This is a real PDF, not a mockup: download the sample PDF. Here's how we made it:

  • Source: the invoice template from the invoice guide, filled with 30 fictional line items, plus the page-number rule from the CSS print guide. The seller, customer, tax IDs and amounts are invented.
  • Renderer: Chrome 157 and Puppeteer 25.9 on a local machine on 13 November 2026. We used the same page.pdf() settings as Screenshotly's renderer (A4, 1 cm margins, background graphics on) and the same request handling, with fullPage: true.
  • Not the production API: production runs a different Chromium build with Linux fonts, so the typeface in your output will differ. The system font stack resolved to San Francisco on our Mac.
  • What it shows: the template's @page margin replaced the 1 cm default, the <thead> repeated on page 2, and the @bottom-center margin box printed the page numbers.

Best practices

  1. Build a dedicated print route (/invoices/:id/print, /reports/:id/print) with print CSS, no navigation and a readiness marker.
  2. Design for A4. If your customers expect US Letter, A4 content printed on Letter paper will be scaled by most print dialogs. Keep important content away from the bottom edge.
  3. Send fullPage: true when the page uses web fonts.
  4. Store the PDF you sent. If a customer asks for it again, send the stored file rather than generating a new one.
  5. Test with your longest document. Short samples hide page-break problems.

Next steps

PDF output is part of the Basic plan. You can create a free account to test image captures first, then upgrade when you're ready to generate PDFs.

pdf
generation
automation
documents

About the Author

Asad Ali

Asad Ali

CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.

Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients

Frequently Asked Questions

What's the difference between screenshot and PDF output?

A PNG, JPEG or WebP screenshot is a picture of the rendered page. PDF output is a paginated document produced by Chromium's print engine: text stays selectable and searchable, and links stay clickable. PDFs use your print CSS; screenshots use your screen CSS.

Can I choose Letter size, landscape or custom margins in the API request?

No. The API has no page-size, orientation or margin fields. Every PDF is A4 with 1 cm margins and background graphics enabled. Your page's own CSS can still change some of this; see the CSS print styling guide for what we observed.

Which plan includes PDF output?

Basic ($14/month) and above. A Free-plan key that requests format pdf receives a 403 response with minimumPlan set to basic.

Can I send raw HTML instead of a URL?

No. The url field is required and must be a public http or https address. Host the document on a route your server controls and pass that URL. format: html is an output format that returns the rendered page source; it is not an input.

How do I handle multi-page content?

You don't need to do anything special. The PDF contains the whole document, split across as many A4 pages as it needs. Control where pages break with CSS such as break-before: page and break-inside: avoid.

Ready to capture your first screenshot?

Get started with 100 free screenshots. No credit card required.

Related Articles