Generate PDF
Generates a PDF from a URL, raw HTML, or a saved Template ID. You must provide exactly one input source.
Machine-readable contract: OpenAPI 3.1 (JSON) · YAML.
Size limits: API requests up to 20 MB, PDFs up to 25 MB, spatial ZIPs up to 39 MB, and
testResults up to 8 KB. See Limits & file sizes for the full
table and the spatial ZIP guidance.
compliance: { pdfUa: 2 } for PDF 2.0 or compliance: { pdfUa: 1 } for PDF 1.7.
Authoring requirements still apply: use semantic HTML, accurate language metadata, table headers,
descriptive link names, and alt text for meaningful figures. Inline SVG figures require image figures with
alt text for assistive-technology support. See
PDF/UA generation for limitations and validation evidence.
curl -X POST "https://api.forkpdf.com/v1/generate-pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "x-project-id: YOUR_PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com",
"format": "A4",
"waitUntil": "domcontentloaded"
}'
# Expected Response:
# {
# "id": "xxxxxxx-ce4a-7104-b6ab-c935e11ac2c5",
# "status": "completed",
# "downloadUrl": "https://api.forkpdf.com/storage/...",
# }
Examples & Outputs
Explore different ways to configure the PDF generation engine based on your required output format.
1. Standard PDF with Data Injection
Pass a JSON data payload to dynamically populate your Nunjucks template and save the resulting PDF locally.
cURL
curl -X POST "https://api.forkpdf.com/v1/generate-pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "x-project-id: YOUR_PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"templateId": "xxxxxxxx-1530-4240-9358-d218f757c586",
"format": "A4",
"data": {
"title": "some another procut",
"subtitle": "Check out our latest premium items.",
"items": [
{ "name": "Ergonomic Keyboard", "price": 129.99 },
{ "name": "Wireless Mouse", "price": 49.99 }
],
"showFooter": true,
"year": 2026,
"companyName": "TechGear Solutions"
}
}'
# Response
# {
# "success": true,
# "message": "File successfully generated and saved.",
# "id": "xxxxxxxx-5e1e-7966-bbe5-a57a088f3fec",
# "status": "completed",
# "downloadUrl": "https://.../result.pdf",
# "sizeBytes": 75285
# }
SDK
const result = await client.generate({
templateId: 'xxxxxxxx-1530-4240-9358-d218f757c586',
format: 'A4',
data: {
title: "some another procut",
subtitle: "Check out our latest premium items.",
items: [
{ name: "Ergonomic Keyboard", price: 129.99 },
{ name: "Wireless Mouse", price: 49.99 }
],
showFooter: true,
year: 2026,
companyName: "TechGear Solutions"
},
outputDir: './output'
});
console.log(result);
/*
{
success: true,
message: 'File successfully generated and saved.',
id: 'xxxxxxx-ce4a-7104-b6ab-c935e11ac2c5',
s3Key: 'results/retention-24h/.../result.pdf',
testResults: null,
downloadUrl: 'https://forkpdf-managed-outputs...',
sizeBytes: 75285,
pdfFilePath: 'output/document.pdf'
}
*/
2. Spatial Output (ZIP Bundle)
Set spatial: true to receive a ZIP archive containing the visual PDF alongside the binary DOM
coordinate layout.
cURL
curl -X POST "https://api.forkpdf.com/v1/generate-pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "x-project-id: YOUR_PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"url": "https://example.com",
"format": "A4",
"waitUntil": "networkidle0",
"spatial": true
}'
# Response
# {
# "success": true,
# "message": "File successfully generated and saved.",
# "id": "xxxxxxxx-9cef-71ef-8b38-9ad2ae57a3cc",
# "status": "completed",
# "downloadUrl": "https://.../result.zip",
# "sizeBytes": 13805
# }
SDK
const result = await client.generate({
url: 'https://example.com',
format: 'A4',
waitUntil: 'networkidle0',
spatial: true,
outputDir: './output'
});
console.log(result);
/*
{
success: true,
message: 'File successfully generated and saved.',
id: 'xxxxxxxx-9cef-71ef-8b38-9ad2ae57a3cc',
s3Key: 'results/retention-24h/.../result.zip',
testResults: null,
downloadUrl: 'https://forkpdf-managed-outputs...',
sizeBytes: 13805,
zipFilePath: 'output/bundle.zip'
}
*/
3. Asynchronous Generation (Webhooks)
Prevent long-running blocking requests by passing webhook: true. The system acknowledges the
queue and delivers the result to your server.
cURL
curl -X POST "https://api.forkpdf.com/v1/generate-pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "x-project-id: YOUR_PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"templateId": "xxxxxxxx-1530-4240-9358-d218f757c586",
"format": "A4",
"data": {
"title": "Q3 report",
"items": ["Revenue", "Expenses"]
},
"webhook": true
}'
# Response
# {
# "success": true,
# "message": "PDF generation queued. You will be notified via webhook.",
# "id": "xxxxxxxx-5e1e-7966-bbe5-a57a088f3fec",
# "status": "pending"
# }
SDK
const result = await client.generate({
templateId: 'xxxxxxxx-1530-4240-9358-d218f757c586',
format: 'A4',
data: templateData,
webhook: true
});
console.log(result);
/*
{
success: true,
message: 'PDF generation queued. You will be notified via webhook.',
id: 'xxxxxxxx-5e1e-7966-bbe5-a57a088f3fec',
status: 'pending'
}
*/
4. Testing Spatial Constraints
Run validation scripts during generation to ensure no UI clipping occurs. Explicit test cases override
template defaults. (Note: Instead of just failing, your script can return a patch object to automatically fix layouts on the fly. See the Autonomous Self-Healing guide).
cURL
curl -X POST "https://api.forkpdf.com/v1/generate-pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "x-project-id: YOUR_PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"templateId": "xxxxxxxx-1530-4240-9358-d218f757c586",
"format": "A4",
"waitUntil": "domcontentloaded",
"testCase": "if (!doc.querySelector(\"h1\")) return { success: false, reason: \"Missing title\" }; return { success: true };",
"data": {
"title": "Q3 report"
}
}'
# HTTP 422 Response
# {
# "error": "Spatial layout constraints failed on the initial render. No patch provided.",
# "testResults": {
# "success": false,
# "reason": "Missing title",
# "total_attempts": 1
# }
# }
SDK
try {
const result = await client.generate({
templateId: 'd71de932-14c0-4dec-983e-2740e71e74ce',
format: 'A4',
waitUntil: 'domcontentloaded',
testCase: 'return {success:false}', // Overrides the internal template test
data: templateData,
});
} catch (error) {
console.error(error.message);
// Output: "API returned 422 Unprocessable Entity - Spatial layout constraints failed."
}
5. Fillable Forms & Memory Buffers
Read the fillable PDF forms guide for supported controls, field naming, targetLang, and limitations.
Embed custom font families and generate interactive PDF forms, returning the raw byte stream directly into a
Node.js Buffer. Note: When using pdfForm: true, you must use the
targetLang parameter to select the underlying font script so user input renders correctly.
Leaving it blank defaults to Latin-based scripts (like English or Dutch), while passing 'hi'
supports Devanagari scripts (like Hindi or Sanskrit).
cURL
curl -X POST "https://api.forkpdf.com/v1/generate-pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "x-project-id: YOUR_PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"templateId": "xxxxxxxx-1530-4240-9358-d218f757c586",
"format": "A4",
"data": {
"title": "Q3 report"
},
"pdfForm": true,
"targetLang": "hi"
}'
# Response
# {
# "success": true,
# "message": "File successfully generated and saved.",
# "id": "xxxxxxxx-7c2a-71ef-8b38-9ad2ae57a3cc",
# "status": "completed",
# "downloadUrl": "https://.../form.pdf",
# "sizeBytes": 48210
# }
# Save the generated form:
# curl -L "https://.../form.pdf" -o form.pdf
SDK
const result = await client.generate({
templateId: 'xxxxxxxx-1530-4240-9358-d218f757c586',
format: 'A4',
waitUntil: 'domcontentloaded',
data: templateData,
pdfForm: true,
targetLang: 'hi', // Embeds Hindi fonts
downloadBuffer: true
});
console.log(result);
/*
{
pdfBuffer: ,
testResults: null
}
*/
6. Custom Page Size
Use the SDK's width/height options for non-standard dimensions; 1.4.9+ converts
them to a CSS @page rule internally. Direct REST calls should use the CSS
@page + preferCSSPageSize form shown in the cURL tab. This example produces an
800×1200px page (600×900pt).
cURL
curl -X POST "https://api.forkpdf.com/v1/generate-pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "x-project-id: YOUR_PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"htmlContent": "<style>@page { size: 800px 1200px; }</style><h1>Custom page size</h1>",
"format": "A4",
"preferCSSPageSize": true,
"margins": {
"top": "20mm",
"right": "20mm",
"bottom": "20mm",
"left": "20mm"
}
}'
# Response
# {
# "success": true,
# "message": "File successfully generated and saved.",
# "id": "xxxxxxxx-7c2a-71ef-8b38-9ad2ae57a3cc",
# "status": "completed",
# "downloadUrl": "https://.../result.pdf",
# "sizeBytes": 41230
# }
SDK
const result = await client.generate({
htmlContent: `<!DOCTYPE html>
<html>
<body><h1>Custom page size</h1></body>
</html>`,
width: '800px',
height: '1200px',
margins: { top: '20mm', right: '20mm', bottom: '20mm', left: '20mm' },
outputDir: './output'
});
Verified: 800×1200px becomes 600×900pt; 20mm margins are ~56pt and the content box is ~650×1050px.
PDF/UA-2 accessibility
Set compliance: { pdfUa: 2 } to generate a tagged PDF 2.0 document with PDF/UA-2 structure
metadata. Add pdfA: '4' for a combined PDF/A-4 + PDF/UA-2 document. The visual layout is
unchanged. Successful responses include x-pdf-ua: 2,
x-font-embedding: verified, x-compliance-status, and
complianceStatus/warnings metadata. complianceStatus.pdfUa reports
stable; warnings contains only advisory authoring or accessibility issues.
PDF/A-4 responses also include x-pdf-a: 4. Add pdfForm: true to keep AcroForm widgets.
PDF/UA requests tag them with Form structure; standalone PDF/A forms remain untagged.
curl -X POST "https://api.forkpdf.com/v1/generate-pdf" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "x-project-id: YOUR_PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"htmlContent": "<h1>Accessible invoice</h1>",
"format": "A4",
"compliance": { "pdfUa": 2 }
}'
Read the PDF/UA generation guide for supported combinations, validation details, error codes, and the current limitations.
Per-element HTML language tags
For PDF/UA-1 and PDF/UA-2, set lang on the <html> element for the document
default and on each element that changes language. ForkPDF preserves those values as per-element PDF
/Lang entries when they differ from the document language. This is separate from
targetLang, which sets the document/form language and selects form fonts.
<html lang="en">
<body>
<h1>Report</h1>
<p lang="fr">Résumé</p>
</body>
</html>
PDF/UA-1 and PDF/A-2/3
The PDF 1.7 path uses compliance: { pdfUa: 1 }. Add pdfA: '2b',
'2u', '2a', '3b', '3u', or '3a'
for a combined PDF/A-2/3 + PDF/UA-1 document. PDF/A and PDF/UA-1 are stable and machine-validated;
representative NVDA + Edge testing is complete. PDF/A-2/3 files use a PDF 1.7 header and are returned with
x-pdf-ua: 1 and x-pdf-a.
To generate standalone PDF/A without a PDF/UA claim, omit pdfUa and send
compliance: { pdfA: '3b' } or another supported flavor. Standalone PDF/A responses
omit x-pdf-ua. Set fontPolicy: 'strict' to reject external stylesheets,
non-inline fonts, and system-font fallback with FONT_POLICY_STRICT.
Accessibility warnings
Successful responses may include x-accessibility-warnings and
x-accessibility-warning-count. The warnings are advisory: they flag authoring issues that can
make a PDF harder to use with assistive technology, but they do not block generation.
The header is base64-encoded JSON:
{
"version": 1,
"count": 1,
"warnings": [
{
"code": "TEXT_LETTER_SPACING",
"severity": "warning",
"message": "Text has letter-spacing. Position-based PDF readers may insert spaces between glyphs.",
"count": 2,
"samples": [{ "selector": "h1", "text": "DATES", "letterSpacing": "2px" }]
}
]
}
Current warning codes include TEXT_LETTER_SPACING, IMAGE_MISSING_ALT,
FIGURE_MISSING_LABEL, INLINE_SVG_FIGURE, LINK_EMPTY_NAME, TABLE_MISSING_HEADERS,
MISSING_TITLE, and MISSING_LANG.
Configuration Options
The generate method takes a single options object (which maps to the JSON payload in the API
request, along with SDK-specific properties like outputDir).
| Parameter | Type | Description |
|---|---|---|
url |
string | The webpage URL to convert to PDF. (Provide exactly one of url, htmlContent, or templateId). |
htmlContent |
string | Raw HTML string to convert to PDF. |
templateId |
string | The UUID of a saved template in your Fork PDF dashboard to render. |
format |
string | Standard paper format (e.g., 'A4', 'Letter'). Required if explicit
width/height are not provided. |
width / height |
string | number | Custom page dimensions (e.g., '8.5in', '800px'). Requires both. Units: px,
in, cm, mm (not pt). SDK 1.4.9+ converts these to CSS @page; direct REST calls should
use @page + preferCSSPageSize. |
landscape |
boolean | Whether to print in landscape orientation. Defaults to false. |
margins |
object | Page margins object: { top, right, bottom, left }. |
waitUntil |
string | When to capture the page. Allowed: 'load', 'domcontentloaded',
'networkidle0', 'networkidle2', 'isProcessed'. Defaults to
'domcontentloaded'. |
timeout |
number | Request timeout in milliseconds. Must be between 3000 and 30000. Defaults
to 10000. |
css |
string | Custom CSS string to inject into the page before rendering. |
js |
string | Custom JavaScript string that is injected and bundled directly into the HTML document to be evaluated as the page renders. |
pdfForm |
boolean | Generate an interactive, fillable PDF form. Defaults to false. Can be combined
with PDF/UA-1/2, standalone PDF/A, or a matching PDF/UA + PDF/A combination. PDF/A-only forms
are not tagged and make no PDF/UA claim. |
compliance |
object | Stable. Generate tagged PDF/UA-1 or PDF/UA-2 output with
{ pdfUa: 1 } or { pdfUa: 2 }, optionally combined with a supported PDF/A
flavor. Can be combined with pdfForm; PDF/A-only forms remain untagged. Per-element HTML
lang values are preserved as PDF /Lang entries. See
PDF/UA generation for authoring requirements, supported layouts,
warnings, and limitations. |
data |
object | JSON data payload to inject into your Nunjucks template (if using templateId or
htmlContent). |
preferCSSPageSize |
boolean | Give priority to CSS page size declarations over the format/dimensions parameters. |
omitBackground |
boolean | Hides default white backgrounds and allows generating PDFs with transparency. |
targetLang |
string | Used with pdfForm and compliance. For forms, injects the correct font so
interactive inputs render. For PDF/UA-1/2, sets the PDF document /Lang and XMP
dc:language. Set HTML lang on individual elements for per-element language
changes. Allowed values: 'en', 'hi', 'th', 'ja',
'zh', 'ko', and 'ar'. |
deviceScaleFactor / zoom |
number | Adjusts the emulated device pixel ratio or standard scaling zoom level before capturing. |
spatial |
boolean | Set to true to extract spatial mapping metadata (returns a zip bundle instead of a
PDF). |
testCase |
string | JavaScript validation script executed after the PDF is rendered to validate its spatial layout. Return a patch object for instant internal self-healing, or custom keys to route dynamic data to your webhook. |
emulateMediaType |
string | Emulates the CSS media type of the page before rendering. Allowed values are 'print' or 'screen'. Defaults to 'print'. |
webhook |
boolean | Process the PDF asynchronously and deliver the payload to your project's configured webhook. (Mutually exclusive with streamOnly). |
streamOnly |
boolean | Bypass the JSON metadata response and directly return the raw file array buffer. (Mutually exclusive with webhook). |
downloadBuffer |
boolean | SDK Only: If true, downloads the file directly into a Node.js memory Buffer.
|
unzip |
boolean | SDK Only: If spatial is true, automatically extracts the downloaded zip bundle
in memory or to disk. |
outputDir |
string | SDK Only: Local directory path to automatically save the generated files. |
signal |
AbortSignal | SDK Only: Cancels generation and any file download it performs. Not sent to the API;
cancellation throws ForkPDFError with code ABORT_ERROR. |
healAttempt |
number | An auto-incrementing counter managed by the server to track self-healing retries. Treat this value as read-only. The server enforces a hard maximum of 100 attempts. Warning: If you drop or reset this value during your webhook retry payload, the count starts over from 0, and your system may get stuck in an infinite loop. Always enforce a smaller maximum limit (e.g., 3 to 5 attempts) inside your client-side webhook handler. |
targetPdfId |
string | Optional UUID identifier used to overwrite an existing failed document. Primarily used within webhook retry loops to seamlessly heal failed spatial layouts without changing the original Tracking ID. |