AGENTS.md — ForkPDF SDK 2.1.0 specification
The authoritative specification for the forkpdf Node.js and TypeScript SDK. Point ChatGPT, Claude, Cursor, or another coding agent at this page when it needs the full contract: parameter whitelists, spatial schema v2 types, V8 sandbox limits, return types, and anti-patterns.
Use this spec with your coding agent
Download the Markdown file into your project root, or keep this page open as the source of truth.
Download AGENTS.mdContents
- 0. Instructions for AI Agents
- Machine-readable API contract
- 1. Overview
- 2. Installation & Initialization
- 3. Golden Rules (Hard Constraints — violations throw ForkPDFError)
- 4. client.generate(options) — Full Reference
- 5. Other Client Methods
- 6. SpatialDocument — Querying Spatial Data
- 7. Error Handling
- 8. TypeScript Recipes
- 8.1 URL → Save to Disk
- 8.2 HTML + Nunjucks Template → Memory Buffer
- 8.3 Async Generation via Webhook
- 8.4 Custom Size, Margins, and Landscape
- 8.5 Dynamic Pages (Manual Capture Trigger)
- 8.6 Spatial Binary Extraction & Node Querying
- 8.7 Fillable, Localized PDF Form
- 8.8 Layout Test Assertions (Pure JS Script)
- 8.9 Manage Documents
- 8.10 Webhook Failure Recovery
- 8.11 Production Express Route Handler
- 9. Anti-Patterns (NEVER do these)
- 10. Defaults & Conventions for Agents
- 11. REST Endpoints Reference
- 12. Complete Example
- 13. AOT Preview
0. Instructions for AI Agents
This file is the authoritative specification for the ForkPDF Node.js and TypeScript SDK. When writing code against this SDK, follow every rule below exactly. The SDK performs strict client-side validation and throws ForkPDFError on any violation. Do not invent options, methods, or response fields that are not documented here.
Machine-readable API contract
The HTTP API is described by OpenAPI 3.1:
- JSON: https://forkpdf.com/openapi.json
- YAML: https://forkpdf.com/openapi.yaml
Use the OpenAPI document for endpoints, authentication headers, request/response schemas, limits, and error codes. This AGENTS.md file covers SDK usage and validation rules.
1. Overview
ForkPDF is a PDF-generation service (API base: https://api.forkpdf.com/v1) that converts URLs, raw HTML, or saved dashboard templates into PDFs — including spatial-layout metadata extraction, PDF/A-2/3/4, PDF/UA-1/2, verified font embedding, fillable AcroForms, webhook delivery, and layout test assertions.
- Package:
forkpdfv2.1.0 (native ESM and CommonJS entry points with bundled TypeScript declarations) - Requires: Node.js 18+ (uses global
fetchandAbortController) - Class Exports:
ForkPDFClient,SpatialDocument,ForkPDFError - Type Exports:
GenerateOptions,GenerateResponse,ComplianceOptions,ComplianceStatus,ComplianceCapabilityStatus,ComplianceCapabilities,ClientOptions,DownloadOptions,ListOptions,Margins,PaperFormat,WaitUntilEvent,SpatialNode,SpatialGeometry,SpatialStyles,SpatialDocumentConfig,SpatialMatrix2D,SpatialRectF,SpatialRectLu,SpatialPageInfo,SpatialBoxMetrics,SpatialBoxFragment,SpatialOffsetMappingUnit,SpatialInlineItem,SpatialBreakOpportunity,SpatialExclusionInterval,SpatialShapedRun,SpatialLineFragment,SpatialLineBox,SpatialInlineFormattingContext - Internal Dependencies:
fflate(zip),protobufjs(spatial binary) — installed automatically - Hard Network Timeout: 120 seconds per request, combined with optional caller cancellation through
GenerateOptions.signal - Transport Retries: Idempotent GET requests retry transient network failures and
408/429/5xxresponses with exponential backoff. Generation POSTs are never retried automatically.
2. Installation & Initialization
npm install forkpdf@2.1.0
ESM (native named imports)
import {
ForkPDFClient,
SpatialDocument,
ForkPDFError,
type GenerateOptions,
type GenerateResponse,
type ComplianceOptions,
type DownloadOptions,
type ListOptions,
type PaperFormat,
type WaitUntilEvent,
type Margins,
type SpatialNode,
type SpatialPageInfo,
type SpatialShapedRun
} from 'forkpdf';
const client = new ForkPDFClient(
process.env.FORKPDF_API_KEY!, // required string, e.g. 'pk_live_...' (throws API_KEY_MISSING if empty)
process.env.FORKPDF_PROJECT_ID! // required UUID string
);
CommonJS
const { ForkPDFClient, SpatialDocument, ForkPDFError } = require('forkpdf');
const client = new ForkPDFClient(
process.env.FORKPDF_API_KEY, // required, e.g. 'pk_live_...' (throws API_KEY_MISSING if empty)
process.env.FORKPDF_PROJECT_ID // required, UUID
);
Both module formats expose the same named exports. Do not use a default-import interop shim.
Never hardcode API keys. Always read them from environment variables.
3. Golden Rules (Hard Constraints — violations throw ForkPDFError)
- Exactly ONE input source per
generate()call:url,htmlContent, ortemplateId. Providing none throwsMISSING_INPUT; providing more than one throwsMUTUALLY_EXCLUSIVE_INPUTS. - Page dimensions are mandatory. Provide
format(typePaperFormat, e.g.'A4'), OR bothwidthANDheight. Width without height throwsMISSING_DIMENSIONS.width/heightaccept px, in, cm, or mm (not pt); SDK 1.4.9+ converts them to a CSS@pagerule internally. Direct REST calls should use CSS@page+preferCSSPageSize. webhookandstreamOnlyare mutually exclusive. Providing both throwsMUTUALLY_EXCLUSIVE_INPUTS.timeoutmust be between 3000 and 30000 (ms). Default: 10000. Out-of-bounds values throwINVALID_TIMEOUT.- Only whitelisted option keys are accepted. Any unknown key throws
INVALID_PARAMETER. data(Nunjucks payload) only works withhtmlContentortemplateId— not withurl.unziponly has effect whenspatial: true.targetLangis used bypdfFormandcompliance; forcomplianceit sets the PDF document language.- Always wrap calls in
try/catchand checkerror instanceof ForkPDFError. - The return shape of
generate()varies based on options (returnsPromise<GenerateResponse>) — see §4.2. Never assume a single shape. - This package is distributed through native ESM and CommonJS entry points with bundled TypeScript declarations (
index.d.ts). Use named imports in ESM and destructuring withrequirein CommonJS. - Test scripts (
testCase) must be written in vanilla JavaScript only — NOT TypeScript. They are transmitted as raw code strings and evaluated directly inside an isolated V8 sandbox (isolated-vm) without any server-side compilation or transpilation step. Any TypeScript syntax (type annotations, interfaces, casts) will trigger a syntax crash. Test scripts must also be strictly synchronous; never useasync/awaitor promises insidetestCase. - Self-healing patches only apply to templated renders. The engine's internal retry loop merges
patchdata into Nunjucks templates (htmlContentwithdataortemplateId). It cannot patch static HTML without templates or raw URLs. targetPdfIdonly overwrites documents in'failed'state. Passing atargetPdfIdof a document that is'completed'or'pending'throws HTTP 409 (INVALID_STATE).- Assertion failures consume 1 credit; system crashes consume 0. If a generation fails because a
testCaseassertion returnedsuccess: false, 1 credit is retained to cover rendering/compute costs, and the second credit is refunded. If the engine crashes (5xx), both credits are refunded. - Spatial correctness traps: the default
geometryis in PDF points (1/72");pagesis 0-indexed; and elementtext_contentis often empty. Schema v2rect_lu,border_box_lu, and other*_lufields are page-local Blink LayoutUnits (1/64 CSS px). Divide by64and applydoc.getPageInfo(page).css_to_pdf_transformto get PDF points. Usebox_fragmentsfor split block elements andifc.lines[].fragments[]for inline spans. Read §6 before writing atestCase. - PDF/UA-1 and PDF/UA-2 are stable; PDF/A-2/3/4 are stable.
compliance: { pdfUa: 2 }maps supported semantic HTML into a PDF 2.0/UA-2 document;pdfUa: 1produces a PDF 1.7/UA-1 document. AddpdfA: '4'for PDF/A-4 with UA-2, orpdfA: '2b' | '2u' | '2a' | '3b' | '3u' | '3a'for PDF/A-2/3 with UA-1. PDF/A can also be requested standalone with no PDF/UA claim. Setlangon<html>for the document default and on individual elements for language changes; PDF/UA output preserves those values as per-element PDF/Langentries when they differ from the document language. 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.fontPolicy: 'strict'rejects external stylesheets, non-inline fonts, and system-font fallback.pdfFormcan be combined with PDF/UA-1/2, standalone PDF/A, and matching PDF/UA + PDF/A combinations. PDF/A-only forms remain untagged and make no PDF/UA claim.
4. client.generate(options) — Full Reference
4.1 TypeScript Definitions & Whitelisted Options
export type PaperFormat =
| 'Letter' | 'Legal' | 'Tabloid' | 'Ledger'
| 'A0' | 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6'
| 'letter' | 'legal' | 'tabloid' | 'ledger'
| 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';
export type WaitUntilEvent =
| 'load'
| 'domcontentloaded'
| 'networkidle0'
| 'networkidle2'
| 'isProcessed';
export interface Margins {
top?: string | number;
right?: string | number;
bottom?: string | number;
left?: string | number;
}
export interface ComplianceOptions {
/** PDF/UA tagging. PDF/UA-1 uses the PDF 1.7 path; PDF/UA-2 uses PDF 2.0. */
pdfUa?: 1 | 2;
/** PDF/A can be standalone or combined with the matching PDF/UA version. */
pdfA?: '2b' | '2u' | '2a' | '3b' | '3u' | '3a' | '4';
}
export type ComplianceCapabilityStatus =
| 'verified'
| 'stable'
| 'machine-validated'
| 'experimental';
export interface ComplianceStatus {
fontEmbedding?: 'verified';
fontPolicy?: 'warn' | 'strict';
pdfA?: ComplianceCapabilityStatus;
pdfAFlavor?: '2b' | '2u' | '2a' | '3b' | '3u' | '3a' | '4';
pdfUa?: ComplianceCapabilityStatus;
pdfUaVersion?: 1 | 2;
}
export interface ClientOptions {
retries?: number; // Additional attempts for idempotent GET requests; default 2, clamped 0–5
retryDelayMs?: number; // Base exponential backoff delay; default 250, clamped 0–5000
}
export interface ComplianceCapabilities {
pdfA: {
status: ComplianceCapabilityStatus;
supported: ('2b' | '2u' | '2a' | '3b' | '3u' | '3a' | '4')[];
standalone: boolean;
};
pdfUa: {
status: ComplianceCapabilityStatus;
supported: (1 | 2)[];
standalone: boolean;
};
combinations: Array<{ pdfUa: 1 | 2; pdfA: '2b' | '2u' | '2a' | '3b' | '3u' | '3a' | '4' }>;
fontEmbedding: { status: 'verified'; policy: ('warn' | 'strict')[] };
forms: { withCompliance: boolean; withPdfUa: boolean; withPdfA: boolean };
}
export interface GenerateOptions {
// Input sources (strictly provide exactly one)
url?: string;
htmlContent?: string;
templateId?: string;
// Dimensions (format OR width + height required)
format?: PaperFormat;
width?: string | number;
height?: string | number;
landscape?: boolean;
margins?: Margins;
preferCSSPageSize?: boolean;
// Rendering
css?: string;
js?: string;
waitUntil?: WaitUntilEvent;
emulateMediaType?: 'print' | 'screen';
deviceScaleFactor?: number;
zoom?: number;
omitBackground?: boolean;
// Content & Templating
data?: Record<string, any>;
pdfForm?: boolean;
/** PDF/UA and PDF/A standards claims. PDF/UA combinations can include pdfForm; PDF/A-only forms are untagged. */
compliance?: ComplianceOptions;
/** Font source policy. Defaults to "warn". */
fontPolicy?: 'warn' | 'strict';
targetLang?: 'en' | 'hi' | 'th' | 'ja' | 'zh' | 'ko' | 'ar' | string;
// Spatial & Testing
spatial?: boolean;
unzip?: boolean;
/**
* Plain JavaScript assertion string executed in a V8 sandbox.
* MUST be written in JavaScript only (no TypeScript syntax).
*/
testCase?: string;
// Delivery & Transport
webhook?: boolean;
streamOnly?: boolean;
timeout?: number; // 3000 to 30000 ms (default 10000)
healAttempt?: number; // API-managed, do not set manually
targetPdfId?: string; // UUIDv7 for retrying/healing failed jobs
// SDK Local Flags (never sent to the API)
outputDir?: string;
downloadBuffer?: boolean;
signal?: AbortSignal; // Cancels generation and any file download it performs
}
export interface GenerateResponse {
// File returns
pdfFilePath?: string;
pdfBuffer?: Buffer;
zipFilePath?: string;
zipBuffer?: Buffer;
binaryFilePath?: string;
binaryBuffer?: Buffer;
// Webhook acknowledgment
success?: boolean;
message?: string;
id?: string;
status?: string;
// Test inspection, compliance & custom keys
testResults?: any;
sizeBytes?: number;
compliance?: ComplianceOptions;
complianceStatus?: ComplianceStatus;
warnings?: string[];
[key: string]: any;
}
Whitelisted Options Reference Table:
| Option | TypeScript Type | Default | Description |
|---|---|---|---|
url |
string |
— | Webpage URL to convert (mutually exclusive with htmlContent, templateId). |
htmlContent |
string |
— | Raw HTML string. Supports Nunjucks templating via data. |
templateId |
string |
— | UUID of a saved template from the ForkPDF dashboard. |
format |
PaperFormat |
— | Standard paper format (case-insensitive; e.g. 'A4', 'Letter'). |
width |
string \| number |
— | Custom width (e.g. '8.5in', 800, '800px'). Overrides format; requires height. Units: px, in, cm, mm. |
height |
string \| number |
— | Custom height (e.g. '11in', 1200, '1200px'). Overrides format; requires width. Units: px, in, cm, mm. |
landscape |
boolean |
false |
Landscape orientation. |
margins |
Margins |
— | Object specifying { top, right, bottom, left } (e.g. '20px', '1in'). |
preferCSSPageSize |
boolean |
false |
CSS @page size wins over width/height/format. |
css |
string |
— | CSS injected into the page before rendering. |
js |
string |
— | JS injected into HTML; evaluated as the page renders. |
waitUntil |
WaitUntilEvent |
'domcontentloaded' |
When to capture: 'load', 'domcontentloaded', 'networkidle0', 'networkidle2', 'isProcessed'. |
emulateMediaType |
'print' \| 'screen' |
'print' |
Emulate CSS media type. |
deviceScaleFactor |
number |
1 |
Pixel density (use 2 or 3 for Retina). |
zoom |
number |
— | Scales the viewport/layout. |
omitBackground |
boolean |
false |
Transparent background instead of white. |
data |
Record<string, any> |
— | JSON payload injected into Nunjucks templates (htmlContent/templateId only). |
pdfForm |
boolean |
false |
Generate fillable AcroForm from HTML form elements. Can be combined with PDF/UA-1/2, standalone PDF/A, and matching PDF/UA + PDF/A combinations. PDF/A-only forms are untagged. |
compliance |
ComplianceOptions |
— | PDF/UA-1/2 and PDF/A-2/3/4 are stable. { pdfUa: 1 } or { pdfUa: 2 } generates tagged output. Add pdfA for PDF/A-2/3 with UA-1 or PDF/A-4 with UA-2, or request PDF/A standalone. Per-element HTML lang values are preserved as PDF /Lang entries. PDF/A combinations with forms are supported; PDF/A-only forms are untagged. See https://forkpdf.com/docs/compliance/capabilities/ |
fontPolicy |
'warn' \| 'strict' |
'warn' |
strict rejects external stylesheets, non-inline fonts, and system-font fallback. |
targetLang |
string |
— | Language font injection for pdfForm, and PDF /Lang/XMP document language for compliance: 'en', 'hi', 'th', 'ja', 'zh', 'ko', 'ar'. Use HTML lang attributes for per-element language changes. |
spatial |
boolean |
false |
Extract spatial layout binary (data.pb); returns a ZIP bundle. |
unzip |
boolean |
false |
Auto-extract spatial ZIP (in memory or to outputDir). |
testCase |
string |
— | Vanilla JavaScript only (no TypeScript). Synchronous assertion script evaluated in a V8 sandbox. |
webhook |
boolean |
false |
Async processing: returns acknowledgment immediately; delivers to webhook URL. |
streamOnly |
boolean |
false |
Bypass S3 storage; stream raw binary result back immediately. |
timeout |
number |
10000 |
Generation timeout in ms (Clamped: 3000–30000). |
healAttempt |
number |
— | Server-managed counter of Tier-2 heal resubmissions per targetPdfId (hard cap 100). Never include it in client calls. |
targetPdfId |
string |
— | UUIDv7 to overwrite an existing failed document in webhook retry loops. |
outputDir |
string |
— | (SDK only) Local directory path to write output files. |
downloadBuffer |
boolean |
false |
(SDK only) Download file into a Node.js Buffer in memory. |
signal |
AbortSignal |
— | (SDK only) Cancel generation and any file download it performs. Cancellation throws ForkPDFError with code ABORT_ERROR. |
Stable PDF/UA note: compliance adds a compliance echo and a capability-level complianceStatus object to the result. PDF/UA-1/2 report stable with pdfUaVersion; PDF/A-2/3/4 report stable with pdfAFlavor. Font embedding is reported as verified when the PDF font postflight passes, and fontPolicy reports warn or strict. warnings is reserved for advisory authoring or accessibility issues; PDF/UA does not add a release-status warning. SDK 2.0.0 removes the deprecated experimental response field and its console warning. Use complianceStatus instead. Representative NVDA + Edge testing is complete, but authoring requirements and document-specific review still apply. Inline SVG figures require image figures with alt text for assistive-technology support. pdfA may be standalone or combined with a compatible pdfUa; pdfForm can be combined with PDF/UA-1/2, standalone PDF/A, and matching PDF/UA + PDF/A combinations; PDF/A-only forms are untagged. Use client.getComplianceCapabilities() or GET /v1/compliance/capabilities for the current matrix. See https://forkpdf.com/docs/compliance/capabilities/.
Compliance errors: INVALID_COMPLIANCE, EMPTY_COMPLIANCE, INVALID_COMPLIANCE_PARAMETER, UNSUPPORTED_COMPLIANCE_STANDARD, UNSUPPORTED_COMPLIANCE_COMBINATION, UNSUPPORTED_PDF_UA_VERSION, PDF_UA1_UNSUPPORTED, PDF_UA2_UNSUPPORTED, PDF_A_UNSUPPORTED, and FONT_POLICY_STRICT (server-side, 422).
Compliance capability lifecycle: UNSUPPORTED_COMPLIANCE_COMBINATION is a permanent part of the compliance contract, not a legacy code. A standard can be known but temporarily unsupported while support is being completed. New PDF/A, PDF/UA, WCAG, or form capabilities report their rollout status in GET /v1/compliance/capabilities; clients should preflight against that endpoint. Feature-gate codes such as COMPLIANCE_FORM_UNSUPPORTED may be used during staged rollouts when a specific combination is not yet enabled. Do not treat these codes as deprecated merely because the current deployment supports the feature.
4.2 Return-Value Matrix (GenerateResponse)
| Flags Set | Returned Properties on GenerateResponse |
|---|---|
webhook: true |
{ success: boolean, message: string, id: string, status: string } |
streamOnly + outputDir |
{ pdfFilePath \| zipFilePath, sizeBytes, testResults? } |
streamOnly + spatial + unzip |
{ pdfBuffer, binaryBuffer, testResults? } |
streamOnly (no outputDir) |
{ pdfBuffer \| zipBuffer, testResults? } |
spatial (no outputDir/downloadBuffer/unzip) |
Raw API JSON (contains downloadUrl) |
spatial + outputDir (± downloadBuffer/unzip) |
{ ...data, binaryFilePath, pdfFilePath, zipFilePath } |
spatial + unzip (no outputDir) |
{ pdfBuffer, binaryBuffer } |
spatial + downloadBuffer only |
{ zipBuffer } |
default + outputDir |
{ ...data, pdfFilePath } |
default + downloadBuffer |
{ pdfBuffer } |
| default (nothing) | Raw API JSON (contains pdfBase64 or downloadUrl) |
Notes:
- streamOnly mode decodes test results from the x-test-results response header into the testResults property. Keep testResults under 8 KB of JSON.
- When compliance is set, all return modes also include complianceStatus (or the same object in x-compliance-status for stream-only responses).
- If neither outputDir nor downloadBuffer is set, the SDK does not download the file — it returns API metadata only.
4.3 The Autonomous Self-Healing Architecture
ForkPDF employs a two-tier self-healing system:
- Tier 1 (Internal Engine Loop — Synchronous): Up to 3 attempts (1 initial render + 2 automated retries) executed entirely within the rendering Lambda before responding.
- Tier 2 (Webhook Overwrite Loop — Asynchronous): Client-side or webhook-driven healing using
targetPdfIdto overwrite failed documents while preserving tracking IDs.
┌───────────────────────────────┐
│ client.generate(...) │
└──────────────┬────────────────┘
│
[Attempt 1: Initial Render]
│
┌──────────────▼────────────────┐
│ Evaluate testCase │
└──────────────┬────────────────┘
│
┌───────────────┴───────────────┐
│ │
{ success: true } { success: false }
│ │
[Return PDF / ZIP] Has .patch &&
Attempt < 3 (Max 2 retries)?
│
┌──────────────┴──────────────┐
YES NO
│ │
[Apply patch to `data`] [Throw 422 Error]
[Attempt 2 or 3 Render] │
│ Webhook Mode?
└──────────────┐ │
│ ┌──────┴──────┐
(Loops back) YES NO
│ │
[Receive Webhook [Surface to
with rawPayloadUrl] User/Agent]
│
[Call generate() with
targetPdfId to heal]
Tier 1: Engine-Level Healing Loop (The 3 Total Attempts)
When testCase is provided, the rendering engine runs up to 3 total attempts (MAX_RETRIES = 2):
- Attempt 1 (
attempt = 0): Base render using providedhtmlContentanddata. - Attempt 2 (
attempt = 1): First self-healing retry if Attempt 1 fails and returns apatchobject. - Attempt 3 (
attempt = 2): Final self-healing retry if Attempt 2 fails and returns a subsequentpatchobject.
The patch Mechanism:
When a spatial assertion fails (e.g. text collision, container overflow, line count exceeded), the testCase script returns a patch map containing updated keys for the Nunjucks data payload.
- The engine merges the patch:
currentData = { ...currentData, ...parsedResult.patch }. - The Nunjucks template is recompiled in a worker thread.
- Puppeteer re-renders the layout and produces a fresh Chromium spatial dump (
data.pb). - The engine re-runs the
testCaseagainst the new layout.
Outcome States:
| Outcome | HTTP Code | Returned Data | Description |
|---|---|---|---|
| Success (any attempt 1–3) | 200 |
PDF / ZIP + x-test-results header |
Layout passed assertions. testResults.total_attempts indicates how many attempts were needed (1, 2, or 3). |
| Max Retries Exhausted | 422 |
{ error, testResults } |
Retried 3 times (initial + 2 patches) but assertions still failed. |
| No Patch Provided | 422 |
{ error, testResults } |
Assertions failed on attempt 1 or 2, but the script did not return a patch object. |
| Script Crash | 422 |
{ error: "Test script execution crashed..." } |
Syntax error (e.g., writing TypeScript inside testCase) or unhandled exception. |
Tier 2: Webhook Overwrite Loop (targetPdfId + healAttempt)
If all 3 internal attempts fail during an asynchronous request (webhook: true), the failure is surfaced through your webhook endpoint with tools for client-side resolution:
{
"id": "018f2d5e-6a31-7000-8000-123456789abc",
"status": "failed",
"error": "Max internal healing retries (2) exhausted. Client intervention required.",
"testResults": {
"success": false,
"total_attempts": 3,
"reason": "Signature box clipped across page boundary"
},
"rawPayloadUrl": "https://s3.../request-payload/raw/project-id/018f2d5e...json?X-Amz-Expires=900"
}
rawPayloadUrl: A secure, 15-minute presigned URL allowing the agent or server to inspect the exact input payload that caused the failure.- Healing via
targetPdfId: Submit repaired HTML or data using the failed document's UUIDv7:
await client.generate({
htmlContent: repairedHtml,
data: repairedData,
format: 'A4',
webhook: true,
targetPdfId: '018f2d5e-6a31-7000-8000-123456789abc' // Preserves original document ID
});
- Safety & Idempotency:
- The server enforces that
targetPdfIdmust currently be in'failed'status (HTTP 409INVALID_STATEthrown if already'completed'). -healAttemptis tracked server-side per document. The server increments it automatically on everytargetPdfIdresubmission and blocks further heals after 100. Never send it from the client. - Repair workflow: when all 3 internal attempts fail, your webhook receives a 15-minute presignedrawPayloadUrl. Fetch the original payload, modify it (swap the template, adjustdata, fix the HTML), and resubmit withtargetPdfId. The returned payload is your repair starting point — you are not expected to resubmit it unchanged. - Preserves downstream tracking and storage URLs so third parties do not receive broken references.
4.4 Writing testCase Scripts (Sandbox Specifications)
The testCase script executes inside a remote isolated V8 context (isolated-vm).
Sandbox Constraints & Rules
- Vanilla JavaScript ONLY (No TypeScript): The engine executes code strings directly in the V8 isolate without
tscor Babel transpilation. Including type annotations (e.g.,let el: any,as SpatialNode, orinterface) causes an immediate JavaScript syntax error and crashes the test run (HTTP 422). - Execution Timeout: 2,000 ms hard cutoff.
- Memory Limit: 512 MB.
- Spatial Input Limit: Up to 64 MB of
data.pbor 100,000 nodes, whichever is reached first. Larger inputs fail with HTTP 413SPATIAL_ISOLATE_TOO_LARGE. - Async Disallowed: Must be purely synchronous code. Do not use
fetch,setTimeout, orPromise. - Globals Provided:
doc: Queryable instance withquerySelectorandquerySelectorAllcapabilities.rawPageMetrics:{ pageWidth, pageHeight, printableWidth, printableHeight, marginTop, marginRight, marginBottom, marginLeft }. Same values asdoc;printableWidth/printableHeightand margins are PDF points.log(...args): Emits debug lines directly to container stdout logs.- Coordinate Space: PDF points (1/72 inch), Cartesian. Origin
(0, 0)is at the bottom-left of the full page;xincreases rightward, andyincreases upward. y = 0is the bottom edge of the paper.y = rawPageMetrics.printableHeightis the top edge of the paper (full page height in points).rawPageMetrics.pageHeightis the CSS content-box height in pixels, not the PDF page height.- Content overflowing downward moves toward
y = 0. pagesis 0-indexed (page 0 = page 1).
Required Return Schema
Tier-1 healing is triggered by the presence of a patch object in the return value. success is not required on healing returns; include reason for diagnostics. A failure return without patch is terminal (Tier 2).
// SUCCESS
return {
success: true,
inspectedElements: 12
};
// FAILURE WITH HEALING PATCH
return {
reason: "Invoice table overflowed onto Page 2",
patch: {
// These keys directly overwrite/merge into client.generate({ data: { ... } })
fontSize: "9px",
lineItemLimit: 5,
compactMode: true
}
};
// TERMINAL FAILURE (NO FURTHER PATCH POSSIBLE)
return {
success: false,
reason: "Required legal disclaimer element is missing from the DOM tree"
};
Custom keys in a successful return are available under testResults in the API response and webhook payload.
Self-Healing testCase Recipe
const htmlContent = `
<style>
.invoice { font-size: {{ fontSize | default('12px') }}; }
.row { height: 30px; }
</style>
<div class="invoice">
<h1>Invoice #{{ invNumber }}</h1>
<div id="items">
{% for item in items %}
<div class="row">{{ item.name }} - \${{ item.price }}</div>
{% endfor %}
</div>
<div id="footer">Thank you for your business.</div>
</div>
`;
// Note: Plain JavaScript only inside the template string (no TS type syntax)
const testCase = `
const footer = doc.querySelector('#footer');
const items = doc.querySelectorAll('.row');
// Rule: Footer must stay on Page 1. `pages` is 0-indexed, so page 1 is index 0.
if (!footer || !footer.pages.includes(0)) {
return {
reason: "Footer pushed to page 2.",
patch: {
fontSize: "10px" // Triggers Tier-1 engine retry with smaller font
}
};
}
// Rule: Ensure text doesn't overlap printable boundaries
if (footer.geometry && footer.geometry.y < (rawPageMetrics.marginBottom || 50)) {
return {
reason: "Footer colliding with bottom margin.",
patch: {
fontSize: "8px"
}
};
}
return { success: true };
`;
const result = await client.generate({
htmlContent,
data: {
invNumber: "1049",
fontSize: "14px", // Engine will step this down to 10px or 8px if overflow occurs
items: [ /* 20 line items */ ]
},
format: 'A4',
spatial: true,
testCase,
downloadBuffer: true
});
4.5 Request Limits, Claim-Check Storage & Billing
- Maximum API Request Payload: 20 MB (HTTP 413
PAYLOAD_TOO_LARGE). Measured in UTF-8 bytes. - Maximum Dashboard Request Body: 15 MB. Template assets (
html + css + js + testCase) are capped at 12 MB (TEMPLATE_ASSETS_TOO_LARGE). - Maximum PDF Output: 25 MB (
OUTPUT_TOO_LARGE). - Maximum Spatial ZIP Output: 39 MB (
OUTPUT_TOO_LARGE). The ZIP containsdocument.pdf+data.pb.data.pbstores element attributes. Inline data URI images are carried in both the request HTML anddata.pb, so they can make the ZIP roughly 2× the PDF and also count toward the 20 MB request limit. Use image URLs where possible; if using inline data URIs, keep the PDF around 18 MB or less. URL images keep the request anddata.pbsmall, so the ZIP stays close to the PDF size. - Maximum Combined Output: 40 MB (PDF/ZIP binary + base64
x-test-resultsheader). - Maximum
testResults: 8 KB of JSON (TEST_RESULTS_TOO_LARGE). It counts toward the 40 MB combined limit. sizeBytes: PDF or ZIP file bytes only. S3 stores the raw bytes with no padding.- SDK version notifications: SDK requests send
X-ForkPDF-ClientandX-ForkPDF-Version. API responses includeX-ForkPDF-SDK-Latest,X-ForkPDF-SDK-Status(currentoroutdated), andX-ForkPDF-SDK-Upgrade-Urlwhen an update is available. The SDK warns once per process. See https://forkpdf.com/docs/sdk/changelog/. - Asynchronous Claim-Check Threshold: If
webhook: trueand payload exceeds 100 KB, edge uploads the payload to S3 and passes a presignedpayloadUrlvia Cloudflare Queues. - Synchronous Claim-Check Threshold: If synchronous and payload exceeds 5.5 MB, it is offloaded via claim-check before invoking the rendering engine.
- Billing Deduction Rules:
- Standard Successful Generation: Consumes 2 credits.
- System Failure / Worker Crash (5xx): 0 credits (full refund).
- Assertion Failure (
testResults.success === false): 1 credit consumed (for compute time); 1 credit refunded.
Full reference: https://forkpdf.com/docs/limits/.
4.6 Webhook Delivery, Signatures & Recovery
Every webhook request includes:
x-webhook-signature: t=<timestamp>,v1=<hex_signature>
import crypto from 'crypto';
const expected = crypto
.createHmac('sha256', webhookSecret)
.update(`${timestamp}.${rawPayloadString}`)
.digest('hex');
const isValid = expected === v1Signature;
- Queue Attempts: Retries up to 3 times (Immediate, +15s, +30s) on non-2xx responses.
- TTL Cutoff: Any webhook pending for >10 minutes is dropped.
- Dead-Letter Storage: Webhooks that fail 3 attempts are preserved in Redis (
failed_webhooks:<projectId>) for 3 days. - Canary-Tested Bulk Retries:
client.retryAllFailedWebhooks()delivers the first item as a canary; only if it succeeds are the rest dispatched with a 1-second delay.
5. Other Client Methods
export interface ListOptions {
limit?: number; // default 10, max 100
page?: number; // default 1
sort?: 'asc' | 'desc'; // default 'desc'
}
export interface DownloadOptions {
outputDir?: string;
}
export interface ClientOptions {
retries?: number; // Additional idempotent GET attempts; default 2, clamped 0–5
retryDelayMs?: number; // Base exponential backoff delay; default 250, clamped 0–5000
}
constructor(apiKey: string, projectID: string, baseUrl?: string, options?: ClientOptions);
// Fetch paginated PDF records
await client.list(options?: ListOptions): Promise<{ data: any[]; meta: any }>;
// Fetch metadata and download URL by ID
await client.get(id: string): Promise<any>;
// Download PDF or Spatial ZIP
await client.download(idOrUrl: string, options?: DownloadOptions): Promise<GenerateResponse>;
// Accepts a PDF UUID or a direct URL. With outputDir -> { pdfFilePath | zipFilePath }
// Without outputDir -> { pdfBuffer | zipBuffer }.
// Discover stable PDF/UA-1/2 and the current compatibility matrix
await client.getComplianceCapabilities(): Promise<ComplianceCapabilities>;
// Permanently delete PDF
await client.delete(id: string): Promise<any>;
// Webhook management
await client.getFailedWebhooks(): Promise<any>;
await client.retryFailedWebhook(id: string): Promise<any>;
await client.retryAllFailedWebhooks(): Promise<any>;
All methods throw ForkPDFError on failure. get, delete, and retryFailedWebhook throw INVALID_INPUT if id is missing or not a string.
Cancellation and safe retries
Pass an AbortSignal to generate() to cancel the generation request and any file download it performs. The signal is a local SDK option and is never included in the JSON payload. An aborted call throws ForkPDFError with code ABORT_ERROR.
const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000);
try {
const result = await client.generate({
htmlContent: '<h1>Long render</h1>',
format: 'A4',
downloadBuffer: true,
signal: controller.signal
});
} catch (error) {
if (error instanceof ForkPDFError && error.code === 'ABORT_ERROR') {
// The caller cancelled the operation.
}
}
Only idempotent GET requests are retried automatically. Transient network failures and 408, 429, and 5xx responses use exponential backoff. retries is the number of additional attempts (default 2, clamped to 0–5), and retryDelayMs is the base delay (default 250, clamped to 0–5000). Generation POSTs are never retried automatically because they are not idempotent.
const client = new ForkPDFClient(apiKey, projectId, undefined, {
retries: 2,
retryDelayMs: 250
});
const capabilities = await client.getComplianceCapabilities();
console.log(capabilities.pdfUa.status); // 'stable'
console.log(capabilities.pdfUa.supported); // [1, 2]
6. SpatialDocument — Querying Spatial Data
Extracted from data.pb when spatial: true.
Units, Indexing, and Text — Read First
| Value | Unit | Meaning |
|---|---|---|
geometry |
PDF points (1/72") | Default combined element box, bottom-left origin of the full page |
printableWidth / printableHeight |
PDF points | Full page size; use these for default geometry math |
pageWidth / pageHeight |
CSS px (~96 DPI) | Content-box layout size; not the PDF page |
margin* |
PDF points | Page margins |
pages |
0-based index | Page 0 = page 1; add 1 for display |
schemaVersion |
number | 2 for schema v2, 0 for legacy payloads |
pageInfos[] |
mixed | Per-page layout rect, media box, margins, and transform |
*_lu |
LayoutUnit (1/64 CSS px) | Page-local v2 rectangle units |
box_fragments[] |
mixed | Per-page boxes for split block elements |
ifc.lines[].fragments[] |
mixed | Per-page line fragments and shaped runs for inline content |
node.geometryis in PDF points. A 100 CSS-pixel box is about 75 points wide.node.pagesis 0-indexed. Add 1 for a human-readable page number.doc.schemaVersionis2for new payloads and0for legacy payloads.doc.pageInfosis empty for legacy payloads. Usedoc.getPageInfo(pageIndex)for v2 page metadata.node.innerTextreturns the full text;node.textChild.text_contentis the first text node and may be partial;node.text_contenton an element is often empty.- For a split block element, use
node.box_fragments[]. Each entry haspage_indexand page-localborder_box_lu. - For an inline span or text node, find its IFC root through
node.ifc_root_index, then filterifcRoot.ifc.lines[].fragments[]by the text node index. Each fragment haspage_index,rect_lu,rendered_text, andruns. - To convert a v2
*_lurectangle to CSS px, divide every value by64. To convert to PDF points, applydoc.getPageInfo(pageIndex).css_to_pdf_transformto all four corners. - To map the default geometry to a raster:
scale = imageWidthPx / doc.printableWidth;xPx = geometry.x * scale;yPx = (doc.printableHeight - geometry.y - geometry.height) * scale. Do not usepageWidth/pageHeight.
TypeScript Interfaces
export interface SpatialGeometry {
x: number; // Distance from left page edge (PDF points)
y: number; // Distance from bottom page edge (PDF points, bottom-left origin)
width: number; // Bounding box width (PDF points)
height: number; // Bounding box height (PDF points)
}
export interface SpatialMatrix2D {
a: number;
b: number;
c: number;
d: number;
e: number;
f: number;
}
export interface SpatialRectF {
x: number;
y: number;
width: number;
height: number;
}
export interface SpatialRectLu {
x: number; // 1/64 CSS px
y: number; // page-local, 1/64 CSS px
width: number;
height: number;
}
export interface SpatialPageInfo {
page_index: number;
layout_rect_css_px?: SpatialRectF;
pdf_media_box_pt?: SpatialRectF;
printable_rect_pt?: SpatialRectF;
margin_top_pt?: number;
margin_right_pt?: number;
margin_bottom_pt?: number;
margin_left_pt?: number;
css_to_pdf_transform?: SpatialMatrix2D;
}
export interface SpatialBoxFragment {
page_index?: number;
fragment_index?: number;
border_box_lu?: SpatialRectLu;
padding_box_lu?: SpatialRectLu;
content_box_lu?: SpatialRectLu;
available_inline_size_lu?: number;
}
export interface SpatialBoxMetrics {
page_index?: number;
border_box_lu?: SpatialRectLu;
padding_box_lu?: SpatialRectLu;
content_box_lu?: SpatialRectLu;
available_inline_size_lu?: number;
max_inline_size_lu?: number;
display?: string;
overflow_x?: string;
is_shrink_to_fit?: boolean;
has_content_dependent_width?: boolean;
width_dependency?: string;
supports_variable_text_reflow?: boolean;
table_layout?: string;
column_inline_sizes_lu?: number[];
}
export interface SpatialOffsetMappingUnit {
dom_start?: number;
dom_end?: number;
ifc_start?: number;
ifc_end?: number;
type?: string;
}
export interface SpatialBreakOpportunity {
ifc_offset?: number;
opportunity?: string;
class_before?: string;
class_after?: string;
is_soft_hyphen?: boolean;
is_whitespace?: boolean;
}
export interface SpatialExclusionInterval {
page_index?: number;
node_index?: number;
rect_lu?: SpatialRectLu;
side?: string;
}
export interface SpatialInlineItem {
inline_item_index?: number;
node_index?: number;
type?: string;
ifc_start?: number;
ifc_end?: number;
dom_start?: number;
dom_end?: number;
inline_size_lu?: number;
text_direction?: string;
bidi_level?: number;
}
export interface SpatialShapedRun {
line_index?: number;
node_index?: number;
inline_item_index?: number;
advance_css_px?: number;
advance_rendered_px?: number;
includes_justification?: boolean;
bidi_level?: number;
resolved_family?: string;
postscript_name?: string;
font_weight?: number;
font_slant?: string;
font_size_px?: number;
font_ascent_px?: number;
font_descent_px?: number;
glyph_ids?: number[];
glyph_advances_px?: number[];
glyph_x_offsets_px?: number[];
glyph_y_offsets_px?: number[];
glyph_char_indices?: number[];
}
export interface SpatialLineFragment {
page_index?: number;
line_index?: number;
ifc_root_index?: number;
node_index?: number;
inline_item_index?: number;
rect_lu?: SpatialRectLu;
baseline_lu?: number;
ifc_start?: number;
ifc_end?: number;
dom_start?: number;
dom_end?: number;
rendered_text?: string;
is_hyphenated?: boolean;
is_atomic_inline?: boolean;
runs?: SpatialShapedRun[];
}
export interface SpatialLineBox {
page_index?: number;
line_index?: number;
ifc_root_index?: number;
rect_lu?: SpatialRectLu;
baseline_lu?: number;
ascent_lu?: number;
descent_lu?: number;
line_available_width_lu?: number;
hang_width_lu?: number;
soft_break?: boolean;
is_forced_break?: boolean;
uses_first_line_style?: boolean;
is_justified?: boolean;
expansion_px?: number;
justification_mode?: string;
fragments?: SpatialLineFragment[];
}
export interface SpatialInlineFormattingContext {
ifc_root_index?: number;
canonical_text?: string;
line_break_strictness?: string;
locale?: string;
has_floats?: boolean;
has_justified_lines?: boolean;
items?: SpatialInlineItem[];
lines?: SpatialLineBox[];
exclusions?: SpatialExclusionInterval[];
break_opportunities?: SpatialBreakOpportunity[];
}
export interface SpatialStyles {
// Legacy fields
font_size?: number;
color?: string;
background_color?: string;
border_color?: string;
direction?: string;
font_family?: string;
margin_top?: number;
margin_right?: number;
margin_bottom?: number;
margin_left?: number;
// Schema v2 resolved styles
font_size_px?: number;
font_weight?: number;
font_style?: string;
italic_angle_deg?: number;
font_stretch_pct?: number;
letter_spacing_px?: number;
word_spacing_px?: number;
line_height_px?: number;
text_indent_px?: number;
hanging_indent_px?: number;
white_space?: string;
overflow_wrap?: string;
word_break?: string;
line_break?: string;
hyphens?: string;
text_align?: string;
text_align_last?: string;
text_justify?: string;
text_transform?: string;
writing_mode?: string;
font_kerning?: string;
text_rendering?: string;
font_feature_settings?: string;
font_variant_ligatures?: string;
font_variant_numeric?: string;
lang?: string;
font_family_list?: string[];
text_wrap?: string;
tab_size_px?: number;
hyphenate_character?: string;
hyphenate_limit_zone_px?: number;
hyphenate_limit_chars?: number;
unicode_bidi?: string;
}
export interface SpatialNode {
index: number;
tag_name: string; // ⚠ snake_case, NOT tagName
has_layout?: boolean;
pages: number[]; // 0-indexed; page 0 = page 1
geometry?: SpatialGeometry; // default combined box, PDF points
styles?: SpatialStyles;
attributes?: Record<string, string>;
text_content?: string; // ⚠ #text nodes only
parent_index?: number;
is_shadow_node?: boolean;
is_image_loaded?: boolean;
// Schema v2 fields
ifc_root_index?: number; // -1 when the node is not in an IFC
box_metrics?: SpatialBoxMetrics | null;
box_fragments?: SpatialBoxFragment[];
ifc?: SpatialInlineFormattingContext | null;
raw_dom_text?: string; // #text nodes only
offset_mapping?: SpatialOffsetMappingUnit[];
// Computed SDK properties:
parentNode: SpatialNode | null;
childNodes: SpatialNode[];
readonly innerText: string;
readonly textChild: SpatialNode | null;
}
export interface SpatialDocumentConfig {
pierceShadowDOM?: boolean;
}
export class SpatialDocument {
schemaVersion: number; // 2 = schema v2, 0 = legacy
pageInfos: SpatialPageInfo[];
pageInfoByIndex: Map<number, SpatialPageInfo>;
load(input: string | Buffer, options?: SpatialDocumentConfig): Promise<void>;
getPageInfo(pageIndex: number): SpatialPageInfo | null;
querySelector(selector: string): SpatialNode | null;
querySelectorAll(selector: string): SpatialNode[];
}
SpatialBreakOpportunity, SpatialExclusionInterval, and SpatialOffsetMappingUnit are also exported; see index.d.ts for the complete declarations.
Usage
import { SpatialDocument, type SpatialNode } from 'forkpdf';
const doc = new SpatialDocument();
await doc.load('./output/data.pb', { pierceShadowDOM: false });
// or: await doc.load(binaryBuffer);
// Page geometry
// PDF page size in points: use these for geometry math
console.log(doc.printableWidth, doc.printableHeight);
// CSS content-box size in px: layout only
console.log(doc.pageWidth, doc.pageHeight);
// Margins are in points
console.log(doc.marginTop, doc.marginRight, doc.marginBottom, doc.marginLeft);
// CSS DOM Queries
const h1: SpatialNode | null = doc.querySelector('h1');
const rows: SpatialNode[] = doc.querySelectorAll('tr.row');
// Map geometry to a raster (e.g. a 150 DPI PNG)
const imageWidth = 1240; // rendered page image width in pixels
if (h1 && h1.geometry) {
const scale = imageWidth / doc.printableWidth;
const xPx = h1.geometry.x * scale;
const yPx = (doc.printableHeight - h1.geometry.y - h1.geometry.height) * scale;
}
Schema v2: page metadata and split elements
This example is self-contained. getSpanFragments() returns one entry per line/page fragment, and
toPdfRect() converts that fragment through its own page transform.
function collectTextIndices(node: SpatialNode, indices = new Set<number>()) {
if (node.tag_name === '#text') {
indices.add(node.index);
return indices;
}
for (const child of node.childNodes) {
collectTextIndices(child, indices);
}
return indices;
}
function getSpanFragments(doc: SpatialDocument, selector: string) {
const span = doc.querySelector(selector);
if (!span) return [];
const ifcRoot = doc.nodes.find((node) => node.index === span.ifc_root_index);
if (!ifcRoot?.ifc) return [];
const textIndices = collectTextIndices(span);
const fragments: SpatialLineFragment[] = [];
for (const line of ifcRoot.ifc.lines ?? []) {
for (const fragment of line.fragments ?? []) {
if (fragment.node_index == null || !textIndices.has(fragment.node_index)) continue;
fragments.push(fragment);
}
}
return fragments;
}
function toCssRect(rect: SpatialRectLu) {
return {
x: rect.x / 64,
y: rect.y / 64,
width: rect.width / 64,
height: rect.height / 64
};
}
function toPdfRect(doc: SpatialDocument, fragment: SpatialLineFragment) {
const page = doc.getPageInfo(fragment.page_index ?? -1);
const t = page?.css_to_pdf_transform;
const r = fragment.rect_lu;
if (!t || !r) return null;
const x0 = t.a * (r.x / 64) + t.e;
const x1 = t.a * ((r.x + r.width) / 64) + t.e;
const y0 = t.d * ((r.y + r.height) / 64) + t.f;
const y1 = t.d * (r.y / 64) + t.f;
return { x0, y0, x1, y1 };
}
// 2 = schema v2, 0 = legacy
console.log(doc.schemaVersion);
console.log(doc.getPageInfo(0)?.css_to_pdf_transform);
// Block element split across pages
const section = doc.querySelector('#terms');
for (const fragment of section?.box_fragments ?? []) {
console.log(fragment.page_index, fragment.border_box_lu);
}
// Inline span split across pages
const fragments = getSpanFragments(doc, '#s24');
console.log(fragments.map((fragment) => ({
page: fragment.page_index,
text: fragment.rendered_text,
css: fragment.rect_lu ? toCssRect(fragment.rect_lu) : null,
pdf: toPdfRect(doc, fragment),
runs: fragment.runs
})));
rect_lu and border_box_lu are page-local. Divide by 64 for CSS pixels, then apply the page transform. Do not use a span's combined geometry for per-page overlays. If node.pages contains multiple pages, use the per-page v2 fragments.
7. Error Handling
export class ForkPDFError extends Error {
code: string;
originalError: any | null;
testResults: any | null;
constructor(message: string, code?: string, originalError?: any, testResults?: any);
}
| Error Code | Trigger Condition |
|---|---|
API_KEY_MISSING |
Constructor received empty or non-string API key. |
INVALID_PARAMETER |
Unknown option key passed to generate(). |
INVALID_TIMEOUT |
timeout parameter outside 3000–30000 ms. |
MUTUALLY_EXCLUSIVE_INPUTS |
Multiple input sources, or webhook + streamOnly combined. |
MISSING_INPUT |
None of url, htmlContent, or templateId provided. |
MISSING_DIMENSIONS |
No format and no width + height pair provided. |
INVALID_WAIT_UNTIL |
Invalid waitUntil option passed. |
INVALID_INPUT |
Missing or invalid id argument in client methods. |
TIMEOUT_ERROR |
Network request exceeded 120-second hard cutoff. |
API_ERROR / NOT_FOUND |
Upstream API error response. |
MALFORMED_API_RESPONSE |
Upstream JSON missing required fields (downloadUrl, etc.). |
NETWORK_FAILURE |
Network/fetch connection dropped (inspect .originalError). |
DOWNLOAD_URL_MISSING / DOWNLOAD_FAILED |
File download from storage failed. |
INVALID_SELECTOR |
Non-string selector passed to doc.querySelectorAll(). |
BINARY_READ_FAILED / DECODE_FAILED |
Protobuf binary decoding failure in SpatialDocument. |
GENERIC_ERROR |
Fallback error code. |
try {
const result = await client.generate({ /* ... */ });
} catch (error) {
if (error instanceof ForkPDFError) {
console.error(`[${error.code}] ${error.message}`);
if (error.testResults) {
console.error('Layout assertions failed:', error.testResults);
}
} else {
throw error;
}
}
8. TypeScript Recipes
8.1 URL → Save to Disk
import { ForkPDFClient, type GenerateResponse } from 'forkpdf';
const client = new ForkPDFClient(process.env.FORKPDF_API_KEY!, process.env.FORKPDF_PROJECT_ID!);
const result: GenerateResponse = await client.generate({
url: 'https://example.com/report',
format: 'A4',
outputDir: './output'
});
console.log('Saved to:', result.pdfFilePath);
8.2 HTML + Nunjucks Template → Memory Buffer
import { ForkPDFClient, type GenerateResponse } from 'forkpdf';
const client = new ForkPDFClient(process.env.FORKPDF_API_KEY!, process.env.FORKPDF_PROJECT_ID!);
const { pdfBuffer }: GenerateResponse = await client.generate({
htmlContent: '<h1>Invoice #{{ num }}</h1><p>Amount: ${{ total }}</p>',
data: { num: '1004', total: 450 },
format: 'Letter',
downloadBuffer: true
});
// pdfBuffer is a Node.js Buffer instance
8.3 Async Generation via Webhook
const ack = await client.generate({
templateId: '7e6b8c9d-1234-4567-89ab-cdef01234567',
format: 'A4',
webhook: true
});
// ack: { success: true, message: '...', id: '...', status: 'pending' }
8.4 Custom Size, Margins, and Landscape
await client.generate({
url: 'https://example.com/poster',
width: '11in',
height: '8.5in',
landscape: true,
margins: { top: '0.5in', right: '0.5in', bottom: '0.5in', left: '0.5in' },
outputDir: './output'
});
8.5 Dynamic Pages (Manual Capture Trigger)
// Target frontend page must run: window.isProcessed = true;
await client.generate({
url: 'https://example.com/dashboard',
format: 'A4',
waitUntil: 'isProcessed'
});
8.6 Spatial Binary Extraction & Node Querying
import { ForkPDFClient, SpatialDocument, type GenerateResponse, type SpatialNode } from 'forkpdf';
const client = new ForkPDFClient(process.env.FORKPDF_API_KEY!, process.env.FORKPDF_PROJECT_ID!);
const { pdfBuffer, binaryBuffer }: GenerateResponse = await client.generate({
htmlContent: '<div class="header"><h1>Invoice</h1><span class="tax">10%</span></div>',
format: 'A4',
spatial: true,
unzip: true,
downloadBuffer: true
});
const doc = new SpatialDocument();
await doc.load(binaryBuffer!);
const taxNode: SpatialNode | null = doc.querySelector('.tax');
if (taxNode && taxNode.geometry) {
console.log(`Tax coordinates: x=${taxNode.geometry.x}, y=${taxNode.geometry.y}`);
console.log(`Page: ${taxNode.pages.join(', ')}`);
}
8.7 Fillable, Localized PDF Form
await client.generate({
htmlContent: '<form><input name="fullName"><textarea name="address"></textarea></form>',
format: 'A4',
pdfForm: true,
targetLang: 'hi' // 'en' | 'hi' | 'th' | 'ja' | 'zh' | 'ko' | 'ar'
});
8.8 Layout Test Assertions (Pure JS Script)
try {
await client.generate({
htmlContent: '<div class="container"><h1>Header</h1></div>',
format: 'A4',
spatial: true,
// IMPORTANT: testCase must be plain JavaScript, never TypeScript
testCase: `
const header = doc.querySelector('h1');
if (!header) return { success: false, reason: "Missing header" };
return { success: true };
`
});
} catch (e: any) {
if (e.testResults) {
console.error('Structured layout failure:', e.testResults);
}
}
8.9 Manage Documents
const page1 = await client.list({ limit: 20, page: 1, sort: 'desc' });
const meta = await client.get('pdf-uuid');
const file = await client.download('pdf-uuid', { outputDir: './downloads' });
await client.delete('pdf-uuid');
8.10 Webhook Failure Recovery
const failed = await client.getFailedWebhooks();
await client.retryFailedWebhook('pdf-uuid');
await client.retryAllFailedWebhooks();
8.11 Production Express Route Handler
import express, { type Request, type Response, type NextFunction } from 'express';
import { ForkPDFClient, ForkPDFError, type GenerateResponse } from 'forkpdf';
const app = express();
const client = new ForkPDFClient(process.env.FORKPDF_API_KEY!, process.env.FORKPDF_PROJECT_ID!);
app.get('/invoices/:id/pdf', async (req: Request, res: Response, next: NextFunction) => {
try {
const { pdfBuffer }: GenerateResponse = await client.generate({
templateId: process.env.INVOICE_TEMPLATE_ID,
data: { invoiceId: req.params.id },
format: 'A4',
downloadBuffer: true
});
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `inline; filename="invoice-${req.params.id}.pdf"`);
res.send(pdfBuffer);
} catch (error) {
if (error instanceof ForkPDFError) {
res.status(error.code === 'NOT_FOUND' ? 404 : 502).json({
error: error.message,
code: error.code,
testResults: error.testResults
});
return;
}
next(error);
}
});
app.listen(3000);
9. Anti-Patterns (NEVER do these)
| ❌ Wrong | Why | ✅ Correct |
|---|---|---|
testCase: "const el: SpatialNode = doc.querySelector('h1');" |
TypeScript syntax inside testCase string — server has no transpiler; throws syntax error (422) |
Write plain JavaScript only: const el = doc.querySelector('h1'); |
testCase: "async () => { ... }" |
V8 sandbox is synchronous; throws error | Synchronous JS returning { success: boolean } |
generate({ url, htmlContent, format: 'A4' }) |
Two input sources → throws MUTUALLY_EXCLUSIVE_INPUTS |
Provide exactly one of url / htmlContent / templateId |
generate({ htmlContent }) |
Missing dimensions → throws MISSING_DIMENSIONS |
Add format: 'A4' (or CSS @page + preferCSSPageSize for custom sizes) |
generate({ url, width: '8in' }) |
height missing → throws MISSING_DIMENSIONS |
Always pair width with height |
generate({ url, format: 'A4', webhook: true, streamOnly: true }) |
Mutually exclusive flags | Pick either webhook: true OR streamOnly: true |
generate({ url, format: 'A4', timeout: 60000 }) |
Out of range (3000–30000 ms) → throws INVALID_TIMEOUT |
Keep timeout between 3000 and 30000 |
generate({ url, format: 'A4', fileName: 'out.pdf' }) |
Unknown option key → throws INVALID_PARAMETER |
Only use whitelisted GenerateOptions keys |
generate({ url, data: {...} }) |
data ignored for URLs |
Use data only with htmlContent or templateId |
node.tagName on a SpatialNode |
Field is snake_case | node.tag_name |
node.geometry treated as CSS pixels |
The default geometry is in PDF points (1/72") | Scale with printableWidth/printableHeight |
rect_lu or border_box_lu treated as CSS pixels |
Schema v2 LayoutUnits are 1/64 CSS px | Divide by 64, then apply css_to_pdf_transform |
node.geometry used for a span that crosses pages |
It is one combined box, not a page-local overlay | Use ifc.lines[].fragments[] for inline content |
page: node.pages[0] in a TOC/signature payload |
pages is 0-indexed; page 1 is 0 |
page: node.pages[0] + 1 |
node.text_content used on an element |
Often empty; text lives on #text nodes |
node.innerText or node.textChild.text_content |
const { pdfBuffer } = await generate({ url, format: 'A4' }) |
Nothing downloaded to memory by default | Add downloadBuffer: true or outputDir |
| Hardcoding API keys | Security hazard | Read from process.env.FORKPDF_API_KEY |
generate({ targetPdfId: id }) on a completed PDF |
Only failed PDFs can be healed (throws HTTP 409) | Verify document status is 'failed' before healing |
| Expecting full refund on failed layout test | Layout tests consume rendering compute | Budget 1 credit for test failures; 0 for crashes |
10. Defaults & Conventions for Agents
- CLI scripts / local batch jobs →
outputDir - Web APIs / HTTP responses →
downloadBuffer: true - Slow rendering or high volume →
webhook: true - Pixel-perfect layout verification →
spatial: true+testCase(pure JS) - Non-Latin fillable AcroForms →
pdfForm: true+targetLang - Multilingual PDF/UA → semantic HTML with
langon<html>and on each element that changes language - PDF/A and PDF/UA →
compliance: { pdfUa: 1, pdfA: '3b' }, standalone{ pdfA: '4' }, orfontPolicy: 'strict'; see https://forkpdf.com/docs/compliance/capabilities/ - Single-page web applications →
waitUntil: 'networkidle0'or'isProcessed' - Retina display resolution →
deviceScaleFactor: 2 - Unspecified paper size →
format: 'A4'
11. REST Endpoints Reference
| Method | Endpoint | Description |
|---|---|---|
POST |
/generate-pdf |
Submit a generation job. |
GET |
/compliance/capabilities |
Public PDF/A and PDF/UA capability matrix. |
GET |
/pdfs?limit&page&sort |
List paginated documents. |
GET |
/pdfs/:id |
Retrieve metadata and download URL. |
GET |
/pdfs/:id/download |
Fetch direct download URL / binary. |
DELETE |
/pdfs/:id |
Delete document from database and storage. |
GET |
/webhooks/failed |
List dead-letter failed webhooks. |
POST |
/webhooks/failed/:id/retry |
Retry a single failed webhook. |
POST |
/webhooks/failed/retry-all |
Bulk retry all failed webhooks via canary test. |
All requests include: Authorization: Bearer <apiKey>, x-project-id: <projectID>, X-ForkPDF-Client: forkpdf-node, X-ForkPDF-Version: 2.1.0.
12. Complete Example
The Q3 report example demonstrates a full 3-attempt flow: layout patch, TOC patch, then verification, with signature coordinates returned in testResults.
- Page: https://forkpdf.com/docs/examples/q3-report/
- It includes the Nunjucks template, data, full
testCase, and downloadable source files.
The invoice example covers the Tier 2 webhook fallback path: https://forkpdf.com/docs/self-healing/
Guides:
- https://forkpdf.com/docs/guides/table-of-contents/
- https://forkpdf.com/docs/guides/prevent-page-breaks/
- https://forkpdf.com/docs/guides/element-coordinates/
- https://forkpdf.com/docs/guides/pdf-generator-api/
13. AOT Preview
ForkPDF AOT compiles observed HTML/CSS layouts into one .fpaot file for offline PDF generation. It is separate from the hosted HTML-to-PDF API and is currently a preview feature (current preview: 0.3.0-preview.1). New 0.3.0 bundles render both trained and changed payloads structurally; legacy exact-map bundles remain loadable. New bundles do not embed raw source PDF/PB payloads. The bundle is self-hosted: generation runs in your Node, worker, or container runtime, with no ForkPDF service in the request path. The Atelier demo exercises carry rows and a payment QR as one example testcase.
- Landing page: https://forkpdf.com/aot/
- Verified example: https://gitlab.com/fork-pdf/aot-atelier
- Runtime:
forkpdf-aot@preview(loadCompiled,loadCompiledBytes) - Compiler:
forkpdf-aot-compiler@preview(fpaotCLI)
At runtime, a payload selects an observed plan, plate, and content profile, executes the compiled testcase, and renders the PDF. Changed strings are measured with the locked text runtime; unobserved line profiles fail closed with E_CONTENT_PROFILE_NOT_FOUND and return the required profile plus a render request. Unobserved layouts return E_MISSING_PLAN. Plates are built offline with bundled PDF.js and @napi-rs/canvas; Inkscape, Poppler, and system fonts are not required. Structural generation emits tagged PDF/UA or PDF/A output when the bundle is compiled with the matching compliance profile; the profile is locked to the bundle, so a different policy fails closed (E_COMPLIANCE_LOCKED) instead of downgrading. Supported profiles include PDF/UA-1, PDF/UA-2, PDF/A-2b/2u/2a, PDF/A-3b/3u/3a, PDF/A-4, and the combined UA + PDF/A profiles. Compile requires Node.js 22.13+; runtime generation supports Node.js 18+ and Workers.