Endpoint reference
POST /api/html-to-pdf
Turn an HTML string into a PDF. A headless browser lays it out, so CSS, images and web fonts come out as they do in a browser print. Returns application/pdf.
What it does not do. It takes HTML text only: there is no URL input, and it never opens a page you point it at. JavaScript is switched off, so scripts do not run and a page that builds itself with JavaScript renders empty. External resources load over https from public hosts only (an http:// URL is upgraded to https by the browser); file:, private or internal addresses and redirects to them are blocked. The PDF is untagged (no accessibility tags or outline), and it makes no PDF/A and no form fields. Frames, iframes, objects, embeds, audio and video are not rendered, and AVIF images are not accepted.
Request
Method: POST. URL: https://pdfops.dev/api/html-to-pdf. Body: application/json, or multipart/form-data where html may be a text field or a file. Up to 4.5 MB per request; html itself is capped lower (below). In JSON, numbers and booleans must be JSON numbers and booleans, not strings. In multipart they are sent as text (true, 0.8, and margin as a number or as JSON).
| Field | Type | Required | Description |
|---|---|---|---|
html | String | Yes | The document, a full page or a fragment, up to 1 MB of UTF-8. Must not be blank. |
page_size | String | No | letter (default, 612 x 792 pt) or a4 (595 x 842 pt). Every CSS @page rule is removed; this field decides. |
landscape | Boolean | No | Landscape orientation. Default false. |
margin | Number or object | No | Page margin in points, 0 to 144. A number applies to all four sides; an object takes top, right, bottom, left and leaves the sides you omit at the default. Default 36 (0.5 inch) on every side. |
print_background | Boolean | No | Print background colors and images. Default true. |
scale | Number | No | Scale of the page content, 0.1 to 2. Default 1. |
The optional X-API-Key header works as on /api/merge: no header is anonymous, 100 requests per IP per month; a valid key uses your tier's quota; an invalid or revoked key returns 401 invalid_api_key. A successful (2xx) call counts 5 requests, because rendering costs more than a plain PDF operation. So 100 anonymous requests are 20 renders and a free key's 250 are 50. Once your request reaches the renderer, every outcome is charged. A render that ran, successful or not, counts 5 requests. A refusal the renderer makes before it starts a browser, and only when the analysis took under 250 milliseconds of CPU (html_too_large, html_too_complex for a structure cap, image_too_large for an inline image), counts 1 request. A document that takes long to analyse counts 5. Counting nothing is reserved for a request the API itself rejects before calling the renderer (invalid JSON, a missing html, a bad parameter, html over its size) and a 503 where the renderer was busy, rejected the call, lost its own browser or never answered. A call that would take you past your limit returns 429 rate_limited instead of running. Check consumption with GET /api/usage.
Response
On success: 200 OK, Content-Type: application/pdf, the PDF as the body, plus two headers: x-pdfops-pages (pages in the PDF) and x-pdfops-blocked-requests (external requests our network policy refused or that failed, plus elements removed before rendering such as frames, scripts and preload or prefetch hints; a request the browser refuses on its own, such as a file: URL, is not counted). The page carries no PDFops footer. Nothing is stored: the document is rendered for the response and not kept.
On any failure: 4xx or 5xx, Content-Type: application/json, body is { "error": "<code>", "details": "<explanation>" }.
Images, fonts and external resources
data:URLs work for images, fonts and stylesheets, in HTML attributes (src,srcset,background, inline SVGhref, stylesheet links) and in CSS (url(), including inside custom properties such as--bg,image-set(),@import). Each one is decoded and checked before the browser sees it. They count toward thehtmlsize cap, and at most 300 distinct ones are allowed (identical content counts once). CSS escapes in identifiers aroundurl()(@\69mport,\69mage-set() are understood; an unquotedurl()whose own name is escaped (\75rl(data:...)) is not, and that image does not render.httpsto a public host works for images, stylesheets and web fonts (for example Google Fonts), on the default port 443: up to 50 requests per document, 40 MB in total, 8 MB for any one file, 500,000 bytes of stylesheets in total. Each file has 8 seconds from start to finish (a slow trickle does not extend it), and all fetching ends with the 15 second render deadline. Compressed (Content-Encoding) responses are refused. A redirect is passed to the browser, which follows it for at most 5 hops; each hop is checked again and counts as a request, and relative URLs in a redirected stylesheet resolve against its final address.http://URLs: anhttp://image in your HTML is upgraded tohttps://by the browser before the request and then follows thehttpsrules above (it is blocked if the host does not answer on https). Anhttp://stylesheet<link>is removed and counted inx-pdfops-blocked-requests. Anhttp://@importor font is never loaded and is not counted. Nothing is ever fetched over plain http.- Blocked and skipped:
file:,blob:,ftp:, WebSocket and any other scheme; a non-default port; a URL with a username or password; a host that is an address on a private, loopback, link-local (including169.254.169.254), shared-address or multicast range, or a name that resolves to one. A blocked request is dropped, the rest of the page still renders, andx-pdfops-blocked-requestscounts it. - Images: the type is read from the file itself, not from its declared type, and for an image request only bytes that pass the checks are served. Supported: PNG, JPEG (baseline, extended, progressive), GIF, WebP and simple SVG. Not supported: animated PNG, AVIF and HEIF, BMP, ICO and TIFF, a GIF or WebP with more than 20 frames, the SVG features listed below, and colour-bitmap and SVG fonts. The checks are strict: the file must be in a plain canonical form (for a JPEG only ordinary header segments before the frame, with fill bytes allowed before a marker; for a GIF every frame inside the logical screen; for a PNG no hidden animation chunk), and anything else is refused, not repaired. Refused images fail the request with
400 unsupported_image(a type or structure that is not accepted) or400 image_too_large(a size cap), and the message names the image: its order of appearance and the first 40 characters of its URL. What a refusal costs: a refusal found in an inlinedata:image is decided before a browser starts and counts 1 request; the same refusal for a fetchedhttpsimage is found after the browser has started and counts 5 requests. If you are unsure whether an image is accepted, inline it as adata:URI, or use PNG or JPEG. The samedata:URI used many times (a logo repeated in a table) is one image and is checked and counted once. Images are limited to 16 megapixels each and 96 megapixels in all, counted for every image response served (a GIF is counted by its logical screen, animated images up to four frames); a missing image is skipped, not fatal (every HTTP status is handled: 2xx with a body is content, anything else, including odd codes such as 299 or 520, is missing and answered at once): any non-2xx status (whatever its body: a 404 that carries AVIF bytes is still a 404), a204, an empty body, or bytes that are not a supported image type (a tracking pixel, a soft-404 HTML page) do not render and are counted inx-pdfops-blocked-requests. The request fails only for bytes that are an image: over a size cap (image_too_large) or in a format or structure that is not accepted (unsupported_image). SVG images are simplified: scripts,<style>sheets and classes, filters, masks, patterns, embedded images and links are removed; inlinestyle="..."colours and strokes are kept. The renderer parses the SVG as XML and draws a new, plain SVG built only fromsvg,g,path,rect,circle,ellipse,line,polyline,polygon,text,tspan,defs,linearGradient,radialGradient,stopandclipPathelements with their presentation attributes (numbers, colours, path data, transform lists,url(#id)for a gradient or clip). Astyleattribute is translated: each declaration whose property is a presentation attribute (fill, stroke, stroke-width, opacity, font-size and similar) and whose value is valid becomes that attribute (the style wins, as in CSS); every other declaration is dropped.<use href="#id">that points inside the same file is expanded into a copy (at most two levels, no cycles, within the 2,000-element cap). Dropped, not translated:<style>elements andclassrules,filter,mask,pattern,image,a,script,foreignObject,symbol, nestedsvg,title,desc,metadata, editor-namespace elements and attributes (Inkscape, Sodipodi, Illustrator),role,aria-*,data-*, comments, and a DOCTYPE. An icon that relies on a style sheet inside the SVG therefore draws in plain black. Aclip-pathis not allowed on or inside aclipPathand at most 32 are kept; a transform that magnifies more than 1,000 times (10,000 down the tree) is dropped. Refused (not repaired): an SVG that is not well-formed XML, declares an entity, has nosvgroot or no size (awidthandheight, or aviewBox), is over 200,000 bytes or 2,000 elements, a viewBox that magnifies over 10,000 times, or has nothing drawable left (unsupported_imageorimage_too_large). Numbers are limited to 20,000, ids to 128 characters,styleattributes to 20,000 bytes each. Astroke-dasharraythat would paint more than about 5,000 dashes on one shape, or 50,000 in an image, is dropped (the shape is drawn solid); this is a sanity filter for SVG images, not a bound on drawing cost, and an inline<svg>element in your HTML has no such filter. A dash array inemor an unknown unit is dropped,%geometry resolves against the image's viewBox, and line caps are drawn as authored (a dotted line isstroke-dasharray="0 6"withstroke-linecap="round"). A negativestroke-width, and atransformwith percentages, a number ending in a dot or a trailing comma, are dropped;stroke-widthinem,ex,rem,vw,q,calc(), upper-casePX, or over 1,000, is dropped too, and so is atransformwith whitespace before the parenthesis (scale (2)). A string that decodes as adata:URL is validated when it sits directly in an image function or an@import; anywhere else where it could reach one (a custom property's value, the arguments of any other function such as avar()orenv()fallback) the whole declaration is removed. A top-level string in an ordinary property is kept as written (content: "Data: 1,234 rows"). What bounds drawing cost is the 16,000,000-byte output limit, the 15-second deadline and the memory watchdog, each refused with a charged error: a heavily dashed image, an image scaled up by CSS, a page of tiled backgrounds or an image repeated many times can end inoutput_too_large,render_timeoutorrender_too_heavy. A small image drawn very large by CSS is not bounded by these numbers; the renderer stops a render that uses too much memory (render_too_heavy). Gradient templates that inherit from another gradient (<linearGradient xlink:href="#a">, as Inkscape writes them) are resolved: the stops and attributes are copied (two levels, no cycles). What SVG images do not support:<style>sheets andclassrules (an icon that relies on them draws in plain black),symbolsprites (a file that only holds symbols renders as an empty image),clipPaththat containsuse,useof another file or of an element that was removed,filter,mask,pattern,imageandforeignObject. Inline<svg>in your HTML is a different path and is not simplified. Fonts: WOFF, WOFF2, TrueType and OpenType files up to 2 MB whose table directory parses and whose declared table sizes are consistent (a WOFF2 may declare at most 8 MiB of tables in all); a font with a bitmap or SVG glyph table (sbix,CBDT,CBLC,EBDT,EBLC,SVG), a collection, or an unknown container is skipped. Colour fonts built from vector layers (COLR) work. - What is removed: before rendering, your HTML is parsed with a standards-compliant parser and
<script>,<iframe>,<frame>,<object>,<embed>,<base>,<template>,<audio>,<video>,<meta http-equiv>and every<link>except stylesheets (whoseintegrityandcrossoriginattributes are dropped, because the stylesheet is rewritten) (includingprefetch,preload,preconnect,dns-prefetch,modulepreloadandprerender) are removed. The page is also served under a content security policy that allows images, stylesheets and fonts over https only, so anything the removal misses does not load. - Fetched resources are analysed with a time limit. Every fetched image, stylesheet and font is checked in a worker with a 1 second limit (and a stylesheet with more than 32 unterminated strings, more than 20,000 CSS parse errors or nesting over 100 levels is refused as too complex, in a fetched stylesheet as in an inline
<style>, astyleattribute or adata:stylesheet). A resource whose analysis times out or fails fails the request withhtml_too_complexand counts 5 requests, because silently leaving a stylesheet out would give a wrong document with a 200. - When the PDF is taken: printing starts when the document's
loadevent fires. Images, stylesheets and fonts that are still loading about 2 seconds after the document is ready, and print-only assets that only start loading at print time, may be missing from the PDF; inline them asdata:URIs when exact output matters. - Navigation: the document cannot navigate: a refresh or a link does nothing. It is rendered at a fixed internal address with no cookies or storage.
- Fonts: Helvetica, Arial, Times, Times New Roman, Courier, Courier New and the generic
sans-serif,serifandmonospacerender as Liberation Sans, Serif and Mono, which have the same metrics as Arial, Times New Roman and Courier New. Other installed fonts are not available; load a web font over https or as a data URI. Latin text only is bundled: CJK and emoji glyphs are not provided. - Page breaks: use CSS
break-after: page(orpage-break-after: always) andbreak-inside: avoid. Every@pagerule (size, margins, margin boxes) is removed, and so is every at-rule that is not@media,@supports,@font-face,@import,@keyframes,@layer,@container,@propertyor@scope(for example@counter-style,@font-feature-values,@namespace,@charset); the page size comes frompage_size, not from@page.
Limits
| Limit | Value | Over the limit |
|---|---|---|
| Request body | 4.5 MB | 413 request_too_large |
html | 1 MB of UTF-8 | html_too_large |
| Output pages | 50 | too_many_pages |
| Output size | 16,000,000 bytes | output_too_large |
| Document structure | 60,000 elements, 30,000 table cells, nesting 128 deep, 200,000 bytes of <style>, 600,000 bytes of style attributes | html_too_complex |
| Image size | 16 megapixels each, 96 in total, 300 distinct data: URLs, 20 frames, 200,000 bytes of SVG | image_too_large |
| Image type | PNG, JPEG, GIF, WebP, simple SVG | unsupported_image |
| Browser memory | about 1.2 GB | render_too_heavy |
| External requests | 50 per document | too_many_resources |
| External bytes | 40 MB in total, 8 MB per file, 500,000 bytes of stylesheets | resources_too_large |
| Render time | 15 seconds | 504 render_timeout |
| Quota | 5 requests once the renderer is reached; 1 for a refusal decided before a browser starts; nothing for your own validation errors, a busy or unreachable renderer, or a browser that died on its own (see above) | 429 rate_limited |
CSS nesting (with or without &: .card { .title { } }, > .x { }, a:hover { }, several levels), @property and @scope are supported. Ignored without an error (the PDF is still made with a 200): a nested rule whose selector starts with -- (browsers read it as a custom property, not a rule), a nested at-rule other than @media, @supports, @container and @scope (so a nested @layer block is removed), and rules nested more than three levels inside a top-level rule (the rules past that depth, and the declarations after them in the same block, are removed). Stylesheets are decoded with the charset of their Content-Type (UTF-8 by default).
The 15 seconds include starting the browser. The first call after a quiet period can take a few seconds longer than later ones; a typical one-page document renders in well under a second once warm. Typical causes of render_timeout are a slow external resource or very heavy styling: inline your images and remove what you do not need.
Error codes
| Error code | Status | Trigger |
|---|---|---|
invalid_json | 400 | Request body isn't parseable JSON. |
invalid_multipart | 400 | The multipart body could not be parsed. |
invalid_body | 400 | The JSON is valid but is not an object. |
missing_html | 400 | html is absent or blank. |
invalid_html | 400 | html is not a string. |
html_too_large | 400 | html is over 1 MB of UTF-8, or over 4.4 MB once JSON-escaped (control characters and quotes grow when encoded). Counts nothing: the API refuses it before the renderer is called. |
invalid_page_size | 400 | page_size is not a4 or letter. |
invalid_parameter | 400 | landscape or print_background is not a boolean, scale is not a number from 0.1 to 2, or margin is not a number from 0 to 144 or an object of such numbers. |
too_many_pages | 400 | The document is longer than 50 pages. Counts 5 requests. |
output_too_large | 400 | The PDF would be over 16,000,000 bytes. Counts 5 requests. A table of ten columns fits about 1,000 rows. |
html_too_complex | 400 | More than 60,000 elements, 30,000 table cells, 200,000 bytes of <style>, 600,000 bytes of style attributes, or nesting over 128 levels, or any stylesheet (inline, style attribute, data: or fetched) with more than 32 unterminated strings, more than 20,000 CSS parse errors or nesting over 100 levels (a fetched resource is refused after the browser started, so that one counts 5 requests): counts 1 request when decided in under 250 milliseconds. A refusal after more than 250 milliseconds of analysis, or an analysis that took over 1 second (documents that take long to analyse): counts 5 requests. |
image_too_large | 400 | An image is over 16 megapixels, the images total over 96 megapixels, a GIF or WebP has more than 20 frames, an SVG is over its size caps, or there are more than 300 distinct data: URLs. The message names the image. Counts 1 request when found in an inline data: image before rendering, 5 requests when found later in a fetched file. |
unsupported_image | 400 | An image is of a type that is not accepted (AVIF, BMP, ICO, TIFF, animated PNG), is malformed, is not in the strict canonical form, or is an SVG that is not well-formed, declares an entity, has no usable size or has nothing drawable left. The message names the image and the reason. Counts 1 request for an inline data: image, 5 requests for a fetched one. |
render_too_heavy | 400 | The browser needed more than about 1.2 GB of memory and was stopped. Counts 5 requests. |
too_many_resources | 400 | The page asks for more than 50 external resources. Counts 5 requests. |
resources_too_large | 400 | The external resources total more than 40 MB, or one is over 8 MB, or the stylesheets total more than 500,000 bytes. Counts 5 requests. |
request_too_large | 413 | The whole request body is over 4.5 MB. |
invalid_api_key | 401 | An X-API-Key header was sent but the key is unknown or revoked. Get a fresh key at /pricing. |
rate_limited | 429 | The per-IP limit (anonymous) or your key's tier quota would be exceeded by this call's 5 requests. Retry-After gives seconds until next calendar month. |
render_failed | 500 | The renderer failed on this document (including a browser that died again after receiving the document a second time). Counts 5 requests. |
renderer_unconfigured | 503 | HTML to PDF is not enabled on this deployment. |
renderer_unavailable | 503 | The renderer did not answer, or its browser died on its own and a retry did not get through. Counts nothing. Retry shortly. |
renderer_busy | 503 | The renderer is at capacity. Retry after the Retry-After seconds. |
render_timeout | 504 | Rendering took longer than 15 seconds. Counts 5 requests. |
Example
A small styled invoice, A4, with a footer line:
curl -X POST https://pdfops.dev/api/html-to-pdf \
-H "Content-Type: application/json" \
-H "X-API-Key: pdfops_live_..." \
-d '{"html": "<!doctype html><style>body{font-family:Arial,sans-serif}h1{color:green}table{width:100%;border-collapse:collapse}td,th{border-bottom:1px solid gray;padding:6px;text-align:left}</style><h1>Invoice 1042</h1><table><tr><th>Item</th><th>Qty</th></tr><tr><td>Widget</td><td>2</td></tr></table><p>Thank you.</p>", "page_size": "a4"}' \
-o invoice.pdf # optional key raises your quota to your tier
An HTML file, landscape, with a 20 point margin, as multipart:
curl -X POST https://pdfops.dev/api/html-to-pdf \
-F "html=@report.html;type=text/html" \
-F "landscape=true" \
-F "margin=20" \
-o report.pdf
Keyless calls work: 100 requests per IP per month with no key, which is 20 renders (or, at 1 request each, 96 refusals: a call needs 5 requests free to start).
Using this for real? A free API key raises the keyless 100 calls per IP to 250 requests a month, with no card.
Code examples
Have an API key? Add an X-API-Key header to any request. It is optional, and it raises your quota from 100/IP/month to your tier's.
JavaScript (Node.js 22+), built-in fetch
import { writeFile } from 'node:fs/promises';
const headers = { 'Content-Type': 'application/json' };
if (process.env.PDFOPS_API_KEY) headers['X-API-Key'] = process.env.PDFOPS_API_KEY; // optional
const res = await fetch('https://pdfops.dev/api/html-to-pdf', {
method: 'POST',
headers,
body: JSON.stringify({
html: '<h1>Hello</h1><p>Rendered by a browser.</p>',
page_size: 'a4',
margin: 48,
}),
});
if (!res.ok) {
const err = await res.json();
throw new Error(`PDFops html-to-pdf failed: ${err.error}: ${err.details}`);
}
await writeFile('hello.pdf', Buffer.from(await res.arrayBuffer()));
Python, requests
import os, requests
headers = {}
if os.environ.get("PDFOPS_API_KEY"):
headers["X-API-Key"] = os.environ["PDFOPS_API_KEY"] # optional
res = requests.post(
"https://pdfops.dev/api/html-to-pdf",
headers=headers,
json={
"html": "<h1>Hello</h1><p>Rendered by a browser.</p>",
"page_size": "a4",
"margin": 48,
},
)
res.raise_for_status()
with open("hello.pdf", "wb") as f:
f.write(res.content)
From an AI agent (MCP)
The hosted MCP server at https://pdfops.dev/api/mcp exposes this as the pdf_html_to_pdf tool. It takes the same fields (margin as a single number) and returns the PDF inline as an application/pdf resource. Each call costs 5 requests of quota there too. See PDFops for AI agents.
Behavioral notes
- HTML only, no scripts. No URL input and no JavaScript. External resources are https only and public hosts only.
- Isolated. Rendering runs in a separate service that holds none of your keys or data and accepts only signed requests from the PDFops API.
- Not byte-identical. The PDF carries the browser's own metadata, and two renders of the same HTML can differ in bytes. For a deterministic generator use
/api/text-to-pdfor/api/invoice. - Nothing is stored. The HTML and the PDF are not kept.
- Failed renders count. Once the renderer is reached every outcome counts 5 requests, except a refusal before a browser starts (1 request), a busy or unreachable renderer, a browser that died on its own, and your own validation errors (including
html_too_large). - One render at a time. Each render has its own instance, so a heavy document cannot slow or break another caller's.
- Limits: 1 MB of HTML, 50 pages, 16,000,000 bytes out, 50 external requests, 15 seconds, 16 megapixels per image.
FAQ
How do I convert HTML to PDF with an API?
POST a JSON body with an html field to https://pdfops.dev/api/html-to-pdf. The response is the PDF. Set page_size, landscape, margin, print_background and scale to change the page.
Can I send a URL instead of HTML?
No. The endpoint takes HTML text only. It never opens a page you point it at. Fetch the page yourself and send its HTML, with images inlined as data URIs or served over https.
Does it run JavaScript?
No. Scripts are switched off, so a page that builds itself with JavaScript renders empty or incomplete. Send HTML that is already complete.
Which external resources load?
Images, stylesheets and fonts over https from public hosts, up to 50 requests and 40 MB in total, and data: images, fonts and stylesheets. Everything else is blocked and skipped: http, file, addresses on private or internal networks, and redirects to them. The PDF is still made, and the x-pdfops-blocked-requests header says how many were skipped.
How much quota does a call use?
A render counts 5 requests, because rendering costs more than a plain PDF operation. Once the renderer is reached every outcome counts, failures included: 5 requests, or 1 for a cheap refusal before a browser starts. Only the API's own validation errors (including html_too_large), a busy, rejecting or unreachable renderer, and a browser that died on its own count nothing.
Related: Markdown, text or CSV to PDF · Generate an invoice PDF · Stamp text on a PDF.
Get a free API key. Keyless calls get 100 requests per IP per month; a free key raises that to 250, with no card. Enter your email and the key arrives in your inbox.