We use cookies

We use cookies to enhance your experience and analyse site usage.

HomeAPI Documentation

API Documentation

Generate PDFs from HTML or any URL with a single POST request.

1

Authentication

All requests require an Authorization header with a Bearer token:

http
Authorization: Bearer YOUR_API_KEY

Get your API key from the Dashboard → API Keys page. Keys start with sk_.

2

Base URL

text
https://api.htmlpdf.dev
3

POST /api/pdf

Generate a PDF from HTML or a URL.

POSThttps://api.htmlpdf.dev/api/pdf

Send a JSON body with either url or html (not both). Returns a PDF binary by default, or JSON/Base64 when specified.

4

Parameters

ParameterTypeDefaultDescription
urlstringURL to navigate and render (provide url OR html, not both)
htmlstringRaw HTML string to render (provide html OR url, not both)
formatstringA4Paper size: A4 | Letter | A3 | A5 | Legal | Tabloid
landscapebooleanfalseLandscape orientation
margin.topstring0.4inTop margin in CSS units (e.g. "1in", "20mm", "40px")
margin.rightstring0.4inRight margin in CSS units
margin.bottomstring0.4inBottom margin in CSS units
margin.leftstring0.4inLeft margin in CSS units
printBackgroundbooleantrueInclude CSS background colors and images
scalenumber1Page scale factor between 0.1 and 2.0
pageRangesstringallPage ranges to include, e.g. "1-3, 5"
preferCSSPageSizebooleanfalseUse the CSS @page size if declared in stylesheet
displayHeaderFooterbooleanfalseEnable header and footer templates
headerTemplatestring""HTML template for page header (requires displayHeaderFooter: true)
footerTemplatestring""HTML template for page footer (requires displayHeaderFooter: true)
emulateMediaTypestringprintCSS media type: "screen" or "print"
waitForSelectorstringCSS selector to wait for before rendering (10s timeout)
waitForTimeoutnumber0Additional wait in ms after page load (max 10000)
responseTypestringbinaryResponse format: "binary" | "base64" | "json"
filenamestringdocument.pdfContent-Disposition filename for binary responses
5

Response types

binary (default)

Returns raw PDF bytes. Headers include Content-Type: application/pdf and Content-Disposition: attachment; filename="document.pdf".

base64

Returns a JSON object with the PDF encoded as a Base64 string:

json
{
  "base64": "JVBERi0xLjQKJeLjz9MKN...",
  "size": 42801
}

json

Returns metadata about the generated PDF:

json
{
  "size": 42801,
  "generatedAt": "2026-03-23T12:00:00.000Z"
}
6

Error responses

All errors return JSON with an error field:

json
{ "error": "Provide either \"url\" or \"html\", not neither." }
StatusMeaning
400Bad Request — missing or invalid parameters
401Unauthorized — missing or invalid API key
408Request Timeout — PDF generation exceeded 30 seconds
429Too Many Requests — monthly quota or rate limit exceeded
500Internal Server Error — retry after a moment
7

Paper sizes reference

FormatMillimetresInches
A3297 × 420 mm11.7 × 16.5 in
A4210 × 297 mm8.27 × 11.7 in
A5148 × 210 mm5.83 × 8.27 in
Letter216 × 279 mm8.5 × 11 in
Legal216 × 356 mm8.5 × 14 in
Tabloid279 × 432 mm11 × 17 in
8

Headers & footers

Set displayHeaderFooter: true and provide headerTemplate or footerTemplate as HTML strings.

Special CSS classes available inside templates:

ClassReplaced with
.pageNumberCurrent page number
.totalPagesTotal page count
.titleDocument title
.urlDocument URL
.dateCurrent date

Example — page numbers in footer:

json
{
  "html": "<h1>Report</h1><p>Content...</p>",
  "format": "A4",
  "displayHeaderFooter": true,
  "footerTemplate": "<div style='font-size:10px; width:100%; text-align:center; color:#666;'>Page <span class='pageNumber'></span> of <span class='totalPages'></span></div>",
  "margin": { "bottom": "0.75in" }
}
9

Rate limits

Each plan has a monthly PDF quota and an hourly rate limit. Exceeding either returns 429. Quotas reset on your billing date.

PlanMonthly PDFsRate limit
Free100/mo10 req/hr
Starter500/mo60 req/hr
Growth2,500/mo300 req/hr
Business10,000/mo1,200 req/hr
Scale50,000/mo6,000 req/hr
Enterprise200,000/mo24,000 req/hr

Check current usage in the Dashboard → Usage page.

10

Code examples

cURL
curl -X POST https://api.htmlpdf.dev/api/pdf \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "html": "<h1>Invoice #1042</h1><p>Total: $249</p>",
    "format": "A4",
    "margin": { "top": "1in", "bottom": "1in", "left": "1in", "right": "1in" }
  }' \
  --output invoice.pdf
Node.js
const response = await fetch('https://api.htmlpdf.dev/api/pdf', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    html: '<h1>Invoice</h1><p>Total: $249</p>',
    format: 'A4',
    margin: { top: '1in', bottom: '1in', left: '1in', right: '1in' },
  }),
})
const pdf = await response.arrayBuffer()
fs.writeFileSync('invoice.pdf', Buffer.from(pdf))
Python
import requests

response = requests.post(
    'https://api.htmlpdf.dev/api/pdf',
    headers={'Authorization': 'Bearer YOUR_API_KEY'},
    json={
        'html': '<h1>Invoice</h1><p>Total: $249</p>',
        'format': 'A4',
        'margin': {'top': '1in', 'bottom': '1in', 'left': '1in', 'right': '1in'},
    },
)
with open('invoice.pdf', 'wb') as f:
    f.write(response.content)
PHP
$ch = curl_init('https://api.htmlpdf.dev/api/pdf');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer YOUR_API_KEY',
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'html' => '<h1>Invoice</h1><p>Total: $249</p>',
        'format' => 'A4',
    ]),
    CURLOPT_RETURNTRANSFER => true,
]);
file_put_contents('invoice.pdf', curl_exec($ch));
Go
payload := map[string]interface{}{
    "html":   "<h1>Invoice</h1><p>Total: $249</p>",
    "format": "A4",
}
body, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST",
    "https://api.htmlpdf.dev/api/pdf",
    bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
pdf, _ := io.ReadAll(resp.Body)
os.WriteFile("invoice.pdf", pdf, 0644)