Forma PDF
SDK API reference
SDK 0.4.0 · JavaScript / TypeScript · browser-side PDF generation. Examples use FormaPDF, the global object from forma-pdf.global.js. With the package installed, import the same functions by name.
Layout & values · SDK functions · Editor methods · AI gateway · Bubble contract
01 / Layout and values
Positions, width and height are in millimeters; font sizes are in points. IDs must be unique and fields must fit their source page. Binding client.name reads the nested object { client: { name: ... } }. Layout and values are separate payloads.
{
"layout": {
"schemaVersion": 1,
"name": "Customer quotation",
"page": {
"size": "A4",
"orientation": "portrait",
"automaticPageBreaks": true
},
"pages": [
{
"id": "page-1",
"background": "#ffffff",
"fields": [
{
"id": "heading",
"type": "text",
"label": "Heading",
"x": 18,
"y": 18,
"width": 174,
"height": 12,
"text": "Quotation",
"style": {
"fontSize": 24,
"color": "#173d32",
"bold": true,
"align": "left"
}
},
{
"id": "customer",
"type": "text",
"label": "Customer",
"binding": "client.name",
"x": 18,
"y": 38,
"width": 174,
"height": 10,
"text": "",
"style": {
"fontSize": 12,
"color": "#173d32",
"bold": false,
"align": "left"
}
},
{
"id": "items",
"type": "table",
"label": "Services",
"binding": "items",
"x": 18,
"y": 60,
"width": 174,
"height": 35,
"fontSize": 10,
"color": "#173d32",
"columns": [
{
"key": "description",
"title": "Service"
},
{
"key": "price",
"title": "Price",
"align": "right"
}
]
},
{
"id": "total",
"type": "text",
"label": "Total",
"binding": "total",
"x": 100,
"y": 110,
"width": 92,
"height": 12,
"text": "",
"style": {
"fontSize": 16,
"color": "#173d32",
"bold": true,
"align": "right"
}
}
]
}
]
},
"values": {
"client": {
"name": "Northstar Co."
},
"items": [
{
"description": "Design services",
"price": "$800.00"
}
],
"total": "$800.00"
}
}Download this complete JSON example
Field contracts
| Parameter | Type / contract | Purpose |
|---|---|---|
| All fields | id, type, label, x, y, width, height; binding optional | type is text, image, line or table. |
| Text | text; style: { fontSize, color, bold, align }; overflow optional | align: left, center, right. overflow: auto or clip. |
| Image | source: string; optional binding | PNG/JPEG data URL, or empty string for an empty placeholder. Remote URLs are not accepted as image content. |
| Line | color: hex; thickness: number | No binding is needed; height and thickness are millimeters. |
| Table | columns: [{ key, title, align? }], fontSize, color; binding to list | Each column key is relative to one row object. Optional headerColor, headerBackground, overflow. |
Page format: size: 'A4' | 'Letter', orientation: 'portrait' | 'landscape', optional automaticPageBreaks. Each entry in pages has id, background and fields. Colors use six-digit hex. The distributed TypeScript declarations define the complete Layout contract, including optional page decoration.
Generate a PDF without an editor
const { layout, values } = await fetch('/docs/api/example.json').then(r => r.json())
const checked = FormaPDF.validateDocumentData(layout, values)
if (!checked.valid) throw new Error(JSON.stringify(checked.errors))
const blob = await FormaPDF.generatePDF(layout, values)
await FormaPDF.downloadPDF(layout, values, 'quotation.pdf')The example URL above belongs to this documentation site. In your application, load the saved JSON from your own database. The two generation calls demonstrate alternatives; use one when issuing a document.
02 / SDK function reference
createEditorView parameters and return type
createEditor(container, options) → FormaEditorMounts the visual editor. It does not create a database or save automatically. Call destroy() when unmounting.
| Parameter | Type / contract | Purpose |
|---|---|---|
| container | HTMLElement | Existing browser element; provide an explicit height. |
| options.layout | Layout | JSON string; required | Validated document structure. |
| options.values | Values | JSON string; optional | Data object; defaults to {}. |
| options.locale | string; optional | en, pt-BR or es; editor default is pt-BR. |
| options.onChange | ({ structure, values }) => void | Observe edits; persist in your own application. |
| options.onLocaleChange | (locale) => void | Observe interface language changes. |
| options.ai | AIEditorOptions; optional | Enable AI template creation. |
generatePDFView parameters and return type
generatePDF(layout, values = {}) → Promise<Blob>Generates application/pdf without mounting the editor and without an AI request. Rejects invalid layouts or incompatible image/table content.
| Parameter | Type / contract | Purpose |
|---|---|---|
| layout | Layout | JSON string | Saved template, including original pages and field bindings. |
| values | Values | JSON string | Nested object matching those bindings. |
downloadPDFView parameters and return type
downloadPDF(layout, values = {}, filename = 'documento.pdf') → Promise<Blob>Downloads the PDF and returns its Blob. Run from a user action.
| Parameter | Type / contract | Purpose |
|---|---|---|
| layout, values | Same as generatePDF | Template and separate document data. |
| filename | string; optional | Browser download filename. |
generateBase64View parameters and return type
generateBase64(layout, values = {}) → Promise<string>Returns raw base64 without a data:application/pdf;base64, prefix. Upload and storage are responsibilities of your application.
| Parameter | Type / contract | Purpose |
|---|---|---|
| layout, values | Same as generatePDF | Template and document data. |
parseLayoutView parameters and return type
parseLayout(input) → LayoutValidates schema, page bounds and unique IDs; returns a normalized object or throws.
| Parameter | Type / contract | Purpose |
|---|---|---|
| input | unknown object | JSON string | Layout schemaVersion 1. |
parseValuesView parameters and return type
parseValues(input) → ValuesParses and validates the data object. Keep nested objects; client.name is a binding path, not the literal key to store.
| Parameter | Type / contract | Purpose |
|---|---|---|
| input | unknown object | JSON string | Object with named data properties. |
pageSizeView parameters and return type
pageSize(layout) → { width, height }Returns physical dimensions in millimeters, including landscape orientation.
| Parameter | Type / contract | Purpose |
|---|---|---|
| layout.page.size | A4 | Letter | Paper format. |
| layout.page.orientation | portrait | landscape | Paper orientation. |
describeDataView parameters and return type
describeData(layout, values) → DataContractDerives fields from bindings. Returns { fields, exampleValues }; fields have path, label, type and optional columns.
| Parameter | Type / contract | Purpose |
|---|---|---|
| layout | Layout | Parsed layout. |
| values | Values | Example or current values. |
validateDocumentDataView parameters and return type
validateDocumentData(layout, values) → { valid, errors, contract }Missing or mismatched data is reported as { path, message } entries. Malformed layout/JSON can throw. Zero, false and empty text are valid scalar values.
| Parameter | Type / contract | Purpose |
|---|---|---|
| layout, values | Object | JSON string | Template and data to check before generation. |
resolveDocumentView parameters and return type
resolveDocument(layout, values = {}) → Promise<PaginatedDocument>Returns { pages }. Each resolved page includes id, sourcePageId, automatic, background and fields. Calculated pages are a rendering plan: save the original layout instead.
| Parameter | Type / contract | Purpose |
|---|---|---|
| layout, values | Object | JSON string | Document before calculated page breaks. |
listTemplatesView parameters and return type
listTemplates() → DocumentTemplate[]Returns copies with id, name, description, accent, layout and values. No arguments. Built-in IDs: proposal, quotation, menu, internal.
No parameters.
getTemplateView parameters and return type
getTemplate(id) → DocumentTemplateReturns a copy with metadata, layout and values. Unknown identifiers throw.
| Parameter | Type / contract | Purpose |
|---|---|---|
| id | proposal | quotation | menu | internal | Built-in template identifier. |
normalizeLocaleView parameters and return type
normalizeLocale(value) → LocaleNormalizes to en, es or pt-BR; unsupported editor locales fall back to pt-BR. This does not translate document content.
| Parameter | Type / contract | Purpose |
|---|---|---|
| value | string | Editor interface language such as en-US or es-MX. |
generateAITemplateView parameters and return type
generateAITemplate(request, options) → Promise<AITemplateResult>Calls your AI gateway and validates its response. Returns layout, values, contract, summary, provider, model, usage and serialized JSON equivalents. Does not apply the result to an editor automatically.
| Parameter | Type / contract | Purpose |
|---|---|---|
| request.provider | openai | anthropic; required | Choose one provider. |
| request.prompt | string, 10–6,000 characters | Describe the template and expected bindings. |
| request.locale | pt-BR | en | es; optional | Defaults to pt-BR. |
| request.sampleValues | Values; optional | Fictional example data whose bindings must be respected. |
| request.model | string; optional | Must match the model allowed by your gateway. |
| options.endpoint | HTTPS URL; optional | Defaults to /api/ai/templates; localhost HTTP is permitted. |
| options.apiKey | string; optional | Transient personal provider key; shared company keys stay in your backend. |
| options.signal | AbortSignal; optional | Defaults to a 310-second timeout. |
createAITemplateClientView parameters and return type
createAITemplateClient(endpoint = '/api/ai/templates', fetcher = fetch) → AITemplateGeneratorReturns an async function (request, { apiKey?, signal }) → AITemplateResult. signal is required when calling this returned function.
| Parameter | Type / contract | Purpose |
|---|---|---|
| endpoint | string; optional | Gateway URL. |
| fetcher | typeof fetch; optional | HTTP adapter for your integration or tests. |
Exported constants and types
exampleLayout, exampleValues and locales are also exported. TypeScript exports include Layout, Field, Values, Page, FormaEditor, EditorOptions, Change, Locale, DocumentTemplate, DataContract, DataField, PaginatedDocument, ResolvedPage, ResolvedField, AITemplateRequest, AITemplateResult, AITemplateGenerator and AIEditorOptions.
03 / Editor instance
const editor = FormaPDF.createEditor(document.getElementById('pdf-editor'), {
layout,
values,
locale: 'en',
onChange: ({ structure, values }) => saveDraft(structure, values)
})
const savedLayout = editor.getEstruct()
const savedValues = editor.getValues()
editor.setDocument(savedLayout, savedValues)saveDraft is your application function, not a Forma PDF method. Implement authenticated persistence and debounce if saving continuously. Give the editor container an explicit height. In React/Next, mount client-side and call destroy() in the effect cleanup.
| Parameter | Type / contract | Purpose |
|---|---|---|
| getEstruct() / getStructure() | none → Layout copy | Returns the original serializable layout. getEstruct is the established spelling; getStructure is an alias. |
| getValues() | none → Values copy | Returns document data separately. |
| getDataContract() | none → DataContract | Returns bound paths and example values. |
| setDocument(layout, values) | layout: unknown, values: unknown → void | Replaces both together with undo support. |
| setLayout(layout) | layout: unknown → void | Changes structure, retaining current values. |
| setValues(values) | values: unknown → void | Changes document data, retaining the layout. |
| generatePDF() | none → Promise<Blob> | Generates the current document. This is an instance method, not a new editor. |
| loadTemplate(id) | built-in template ID → void | Replaces the current layout and example values with a starter template. |
| getLocale() | none → Locale | Returns current editor language. |
| setLocale(locale) | string → void | Changes editor interface language without translating the PDF data. |
| onChange(listener) | (change: { structure, values }) => void → unsubscribe function | Subscribe to edits; call the returned function to remove the listener. |
| destroy() | none → void | Releases listeners, observers and UI on unmount. |
04 / Optional GPT / Claude gateway
PDF generation does not require AI. To create templates with AI, configure your own compatible gateway. Managed hosting and provider credits are not included in the SDK license.
POST https://your-gateway.example/api/ai/templates
Content-Type: application/json
X-Provider-Key: user-supplied-key
{
"provider": "openai",
"prompt": "Create a quotation using client.name, items and total from the supplied data.",
"locale": "en",
"sampleValues": {
"client": {
"name": "Northstar Co."
},
"items": [
{
"description": "Design services",
"price": "$800.00"
}
],
"total": "$800.00"
}
}Use provider: 'anthropic' for Claude. Never send a key in the URL or save it in layout/values. A private company key or gateway Bearer token belongs on your backend.
{
layout: Layout,
values: Values,
layout_json: string,
values_json: string,
data_contract_json: string,
contract: { fields: [{ path, label, type, columns? }], exampleValues: Values },
summary: string,
provider: 'openai' | 'anthropic',
model: string,
usage: { inputTokens: number, outputTokens: number }
}The response above is a type sketch, not literal JSON. HTTP errors use { "error": { "code": "...", "message": "..." } }. Display failures, preserve the previous document and do not repeat paid requests automatically. Apply a proposed result with editor.setDocument(result.layout, result.values) only after user confirmation.
AI editor options
| Parameter | Type / contract | Purpose |
|---|---|---|
| endpoint | string; optional | Gateway URL used by the default client. |
| credentials | user | host | user shows the personal-key input. host hides it; your backend must handle authentication and key injection. |
| generate | AITemplateGenerator; optional | Override the gateway call with your own async adapter. Receives (request, { apiKey?, signal }). |
| disclosure | string; optional | Display a disclosure appropriate to your integration. |
05 / Bubble inputs and outputs
| Parameter | Type / contract | Purpose |
|---|---|---|
| Element properties | layout_json, values_json, locale, enable_ai, ai_endpoint, ai_credentials | JSON fields are text; enable_ai is yes/no. |
| Layout output | structure_json | Save this state to your template record. Input is layout_json; output is structure_json. |
| Other states | values_json, data_contract_json, ai_summary, error_message | Save values separately. Show errors in the interface. |
| Progress and PDF states | is_generating, is_creating_template, pdf_url, pdf_base64 | pdf_url is a temporary Blob URL, not permanent storage. |
| Events | structure_changed, template_ready, pdf_ready, error | Connect workflows to these events. |
| Get structure action | no parameters | Publishes current structure, values and data contract. |
| Generate PDF action | download: yes/no, return_base64: yes/no, filename: text | Publishes PDF states and triggers pdf_ready. |
| Create AI template action | provider, prompt, api_key, endpoint, locale; model optional | Applies directly and triggers template_ready. Use the internal AI dialog when a preview and confirmation are needed. |
Open the illustrated Bubble tutorial → · Read the agent implementation manual →