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

ParameterType / contractPurpose
All fieldsid, type, label, x, y, width, height; binding optionaltype is text, image, line or table.
Texttext; style: { fontSize, color, bold, align }; overflow optionalalign: left, center, right. overflow: auto or clip.
Imagesource: string; optional bindingPNG/JPEG data URL, or empty string for an empty placeholder. Remote URLs are not accepted as image content.
Linecolor: hex; thickness: numberNo binding is needed; height and thickness are millimeters.
Tablecolumns: [{ key, title, align? }], fontSize, color; binding to listEach 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) → FormaEditor

Mounts the visual editor. It does not create a database or save automatically. Call destroy() when unmounting.

ParameterType / contractPurpose
containerHTMLElementExisting browser element; provide an explicit height.
options.layoutLayout | JSON string; requiredValidated document structure.
options.valuesValues | JSON string; optionalData object; defaults to {}.
options.localestring; optionalen, pt-BR or es; editor default is pt-BR.
options.onChange({ structure, values }) => voidObserve edits; persist in your own application.
options.onLocaleChange(locale) => voidObserve interface language changes.
options.aiAIEditorOptions; optionalEnable 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.

ParameterType / contractPurpose
layoutLayout | JSON stringSaved template, including original pages and field bindings.
valuesValues | JSON stringNested 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.

ParameterType / contractPurpose
layout, valuesSame as generatePDFTemplate and separate document data.
filenamestring; optionalBrowser 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.

ParameterType / contractPurpose
layout, valuesSame as generatePDFTemplate and document data.
parseLayoutView parameters and return type
parseLayout(input) → Layout

Validates schema, page bounds and unique IDs; returns a normalized object or throws.

ParameterType / contractPurpose
inputunknown object | JSON stringLayout schemaVersion 1.
parseValuesView parameters and return type
parseValues(input) → Values

Parses and validates the data object. Keep nested objects; client.name is a binding path, not the literal key to store.

ParameterType / contractPurpose
inputunknown object | JSON stringObject with named data properties.
pageSizeView parameters and return type
pageSize(layout) → { width, height }

Returns physical dimensions in millimeters, including landscape orientation.

ParameterType / contractPurpose
layout.page.sizeA4 | LetterPaper format.
layout.page.orientationportrait | landscapePaper orientation.
describeDataView parameters and return type
describeData(layout, values) → DataContract

Derives fields from bindings. Returns { fields, exampleValues }; fields have path, label, type and optional columns.

ParameterType / contractPurpose
layoutLayoutParsed layout.
valuesValuesExample 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.

ParameterType / contractPurpose
layout, valuesObject | JSON stringTemplate 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.

ParameterType / contractPurpose
layout, valuesObject | JSON stringDocument 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) → DocumentTemplate

Returns a copy with metadata, layout and values. Unknown identifiers throw.

ParameterType / contractPurpose
idproposal | quotation | menu | internalBuilt-in template identifier.
normalizeLocaleView parameters and return type
normalizeLocale(value) → Locale

Normalizes to en, es or pt-BR; unsupported editor locales fall back to pt-BR. This does not translate document content.

ParameterType / contractPurpose
valuestringEditor 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.

ParameterType / contractPurpose
request.provideropenai | anthropic; requiredChoose one provider.
request.promptstring, 10–6,000 charactersDescribe the template and expected bindings.
request.localept-BR | en | es; optionalDefaults to pt-BR.
request.sampleValuesValues; optionalFictional example data whose bindings must be respected.
request.modelstring; optionalMust match the model allowed by your gateway.
options.endpointHTTPS URL; optionalDefaults to /api/ai/templates; localhost HTTP is permitted.
options.apiKeystring; optionalTransient personal provider key; shared company keys stay in your backend.
options.signalAbortSignal; optionalDefaults to a 310-second timeout.
createAITemplateClientView parameters and return type
createAITemplateClient(endpoint = '/api/ai/templates', fetcher = fetch) → AITemplateGenerator

Returns an async function (request, { apiKey?, signal }) → AITemplateResult. signal is required when calling this returned function.

ParameterType / contractPurpose
endpointstring; optionalGateway URL.
fetchertypeof fetch; optionalHTTP 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.

ParameterType / contractPurpose
getEstruct() / getStructure()none → Layout copyReturns the original serializable layout. getEstruct is the established spelling; getStructure is an alias.
getValues()none → Values copyReturns document data separately.
getDataContract()none → DataContractReturns bound paths and example values.
setDocument(layout, values)layout: unknown, values: unknown → voidReplaces both together with undo support.
setLayout(layout)layout: unknown → voidChanges structure, retaining current values.
setValues(values)values: unknown → voidChanges 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 → voidReplaces the current layout and example values with a starter template.
getLocale()none → LocaleReturns current editor language.
setLocale(locale)string → voidChanges editor interface language without translating the PDF data.
onChange(listener)(change: { structure, values }) => void → unsubscribe functionSubscribe to edits; call the returned function to remove the listener.
destroy()none → voidReleases 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

ParameterType / contractPurpose
endpointstring; optionalGateway URL used by the default client.
credentialsuser | hostuser shows the personal-key input. host hides it; your backend must handle authentication and key injection.
generateAITemplateGenerator; optionalOverride the gateway call with your own async adapter. Receives (request, { apiKey?, signal }).
disclosurestring; optionalDisplay a disclosure appropriate to your integration.

05 / Bubble inputs and outputs

ParameterType / contractPurpose
Element propertieslayout_json, values_json, locale, enable_ai, ai_endpoint, ai_credentialsJSON fields are text; enable_ai is yes/no.
Layout outputstructure_jsonSave this state to your template record. Input is layout_json; output is structure_json.
Other statesvalues_json, data_contract_json, ai_summary, error_messageSave values separately. Show errors in the interface.
Progress and PDF statesis_generating, is_creating_template, pdf_url, pdf_base64pdf_url is a temporary Blob URL, not permanent storage.
Eventsstructure_changed, template_ready, pdf_ready, errorConnect workflows to these events.
Get structure actionno parametersPublishes current structure, values and data contract.
Generate PDF actiondownload: yes/no, return_base64: yes/no, filename: textPublishes PDF states and triggers pdf_ready.
Create AI template actionprovider, prompt, api_key, endpoint, locale; model optionalApplies 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 →