Generate PDF
Generates a PDF from a URL, raw HTML, or a saved Template ID. You must provide exactly one input source.
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.
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.
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.
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).
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
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).
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
}
*/
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'). Required if format is not
provided. |
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. |
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 exclusively with pdfForm. Injects correct fonts ensuring interactive PDF form inputs properly support text in that specific language. Allowed
values: 'en', 'hi', 'th', 'ja', 'zh', and 'ko'.
|
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. |
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. |