Disclosure: I develop Forma PDF, the commercial SDK used below. This article was prepared with AI assistance, and the API names and sample bindings were checked against the source code.
A quotation screen often needs a customer name, a list of services and a download button. The person designing the quotation needs a different interface: a way to position fields, adjust branding and decide where the table goes.
You can build those screens around the same document template. Store its layout as JSON, then supply each quotation's values when generating the PDF.
This walkthrough uses Forma PDF to implement that separation in browser JavaScript. We will start with a download button, add a visual editor for template authors, persist the layout, validate incoming data and work through the decisions needed for a multi-user application.
The example is a service quotation, but the same structure can support proposals, menus and internal documents. What changes between those workflows is the template and its data contract.
What we are building
Imagine a small agency application. An administrator designs a quotation with the agency's branding. A team member opens a customer record, selects services and downloads a PDF. Next week, the administrator changes the footer without rewriting the customer screen.
There are three different objects in that workflow:
| Object | Contains | Lifecycle |
|---|---|---|
| Layout | Page settings, positions, styling, bindings and original pages | Edited by the template author and saved for reuse |
| Values | Customer details, service rows and formatted totals | Supplied for each quotation |
| Generated PDF | The rendered document, including calculated continuation pages | Downloaded or stored as an output file |
Keeping these objects separate gives your app a clear place to make each change. Moving the customer name is a layout change. Choosing another customer is a values change. Saving the final document is a file-storage operation.
This also lets you decide who sees the editor. You can expose it to internal administrators, offer it to customers who need customization, or build templates yourself and ship only the download flow.
Set up the SDK files
The examples assume you have the licensed SDK distribution. Copy its contents into a directory served as /sdk/, preserving the sibling chunks and other assets. The SDK is not currently distributed through npm.
Use a local HTTP development server rather than opening an HTML file directly from disk. Load the code below as JavaScript modules.
The public playground lets you explore the editor before purchasing a license.
For the examples, use two pages on the same origin: one for template management and another for downloading quotations. A minimal file arrangement could look like this:
public/
sdk/
forma-pdf.js
forma-pdf.css
…remaining distribution files
template.html
quotation.html
template.js
quotation.js
Put the editor code in template.js and load it with <script type="module" src="/template.js"></script>. Put the download code in quotation.js and load that module on quotation.html. Include each page's HTML elements before its script tag.
Keep the remaining SDK distribution files together. The ESM build loads PDF engine and font assets when needed, so copying just the entry-point JavaScript is not a complete installation.
Generate a quotation from a template
Start with the built-in quotation template and provide values that match its bindings:
import { getTemplate, downloadPDF } from '/sdk/forma-pdf.js'
const template = getTemplate('quotation')
const values = {
client: {
name: 'Example Studio',
email: 'hello@example.com'
},
quote: {
title: 'Website design proposal',
reference: 'QUOTE-001',
total: '$1,200.00',
terms: 'Payment: 50% on approval and 50% on delivery.'
},
items: [
{ service: 'Discovery', quantity: '1', price: '$300.00' },
{ service: 'Design', quantity: '1', price: '$900.00' }
]
}
const button = document.querySelector('#download-pdf')
const status = document.querySelector('#pdf-status')
button.addEventListener('click', async () => {
button.disabled = true
status.textContent = 'Generating PDF…'
try {
await downloadPDF(template.layout, values, 'quotation.pdf')
status.textContent = 'PDF generated. Download requested.'
} catch {
status.textContent = 'Could not generate the PDF. Please try again.'
} finally {
button.disabled = false
}
})
The page needs these elements before the module runs:
<button id="download-pdf" type="button">Download quotation</button>
<p id="pdf-status" role="status"></p>
The template binds text to paths such as client.name and its table to items. The columns use service, quantity and price.
The sample company and email are fictional. In your app, supply the authorized record's values. Calculate totals in your business logic before passing them to the SDK; formatted price strings are display data.
The starter template includes Portuguese labels and branding. Edit those separately for an English document. Switching the editor's interface language does not translate document content.
Map application records to document values
Your database will probably use a different shape from the template. An order may contain customer.displayName, while the template expects client.name. Keep that translation in a dedicated function rather than scattering it across click handlers and editor callbacks.
Here is an example adapter for an application that stores USD amounts in integer cents. Its input is assumed to have already passed your application's business validation:
const currency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
})
function toQuotationValues(record) {
return {
client: {
name: record.customer.displayName,
email: record.customer.email ?? ''
},
quote: {
title: record.title,
reference: record.reference,
total: currency.format(record.totalCents / 100),
terms: record.paymentTerms ?? ''
},
items: record.lines.map(line => ({
service: line.description,
quantity: line.quantity,
price: currency.format(line.lineTotalCents / 100)
}))
}
}
The adapter formats a total calculated by the application. It does not introduce a second pricing engine inside the PDF layer. Discounts, taxes, rounding and authorization belong to the same business logic that governs the quotation elsewhere in your product.
Notice the use of ?? for optional values. A fallback such as value || '' also replaces 0 and false, which may be meaningful document data. Treat missing values separately from valid falsy values.
If your template's bindings change, this adapter is one place to update and review. If the customer database changes, the PDF template can remain stable as long as the adapter still produces the same contract.
Add an editor for template authors
On a separate template-management page, load the editor stylesheet and provide a container:
<link rel="stylesheet" href="/sdk/forma-pdf.css">
<div id="template-editor"></div>
<button id="save-template" type="button">Save template locally</button>
<p id="save-status" role="status"></p>
Mount the editor and save a snapshot when the author clicks the button:
import { createEditor, getTemplate } from '/sdk/forma-pdf.js'
const template = getTemplate('quotation')
const editor = createEditor(document.querySelector('#template-editor'), {
layout: template.layout,
values: template.values,
locale: 'en'
})
document.querySelector('#save-template').addEventListener('click', () => {
const status = document.querySelector('#save-status')
try {
localStorage.setItem(
'quotation-layout',
JSON.stringify(editor.getStructure())
)
status.textContent = 'Template saved in this browser.'
} catch {
status.textContent = 'Could not save the template in this browser.'
}
})
Local storage makes the example easy to try across pages on the same origin. It is browser-local storage, not shared persistence for your customers. For production, save the layout through your application's authenticated storage layer.
Call editor.destroy() when your application removes the editor, such as during component unmount.
The SDK's layout and values getters return independent copies. Saving a layout snapshot does not require handing your persistence layer a mutable reference to the editor's internal state.
For this walkthrough, save explicitly when the author clicks the button. If you later implement autosave, debounce writes and make save failures visible. Moving one field through a series of pointer events should not create an uncontrolled stream of database writes.
Reuse the saved layout
On the download page, replace the template.layout argument in the first example with the saved layout:
const storedLayout = localStorage.getItem('quotation-layout')
if (!storedLayout) {
throw new Error('Save a quotation template first.')
}
const savedLayout = JSON.parse(storedLayout)
await downloadPDF(savedLayout, values, 'quotation.pdf')
Place this inside the existing click handler's try block so missing or invalid data produces the visible error message.
You can now change the values for the next quotation while keeping the same saved layout. If an author changes bindings, update the data mapping to match.
For workflows that need the file rather than an immediate download, generatePDF(layout, values) returns a Promise<Blob>. Your application can then upload that Blob through its own authorized storage workflow.
Validate the template's data contract
A valid JSON object can still be wrong for a document. For example, items might be an object when the table expects a list, or a row might have description while the template expects service.
Forma PDF exposes a contract derived from the layout's bindings. You can inspect it before connecting a template to your application:
import {
describeData,
getTemplate,
validateDocumentData
} from '/sdk/forma-pdf.js'
const template = getTemplate('quotation')
const contract = describeData(template.layout, template.values)
console.table(contract.fields.map(field => ({
path: field.path,
type: field.type,
columns: field.columns?.map(column => column.path).join(', ') ?? ''
})))
const result = validateDocumentData(template.layout, template.values)
if (!result.valid) {
throw new Error(
result.errors.map(error => `${error.path}: ${error.message}`).join('\n')
)
}
This is a separate inspection example. In your download handler, call validateDocumentData(savedLayout, values) inside the existing try block before generation, using the actual selected layout and mapped record.
The validator reports missing bound values and incompatible types, including table-cell paths. It is not your application's business validator: it does not establish whether an email address is deliverable, whether a price is authorized or whether a total matches the service rows. Malformed layout input can also throw, which is another reason to keep validation inside the error-handling boundary.
For an authoring interface, editor.getDataContract() provides the contract for the editor's current document. That can help you display the data paths an integration must supply.
Move from local storage to shared persistence
Local storage is enough to demonstrate the flow in one browser. A multi-user product needs an application-owned storage model.
One possible model uses three records:
| Record | Example fields | Purpose |
|---|---|---|
| Template | ID, workspace ID, name, current revision | Identifies the reusable document design |
| Template revision | Template ID, revision number, layout JSON, creator, timestamp | Preserves a specific design |
| Document record | ID, template revision, values snapshot, optional PDF storage key | Connects a business document to the design and data used |
This is a suggested host-application model, not a database feature supplied by the SDK.
When an author saves a new revision, keep the previous revision available if existing documents need it. When someone downloads a quotation, your application loads the authorized revision and the values for that quotation, then passes both to the generator.
Choose deliberately between rendering with today's template and rendering with the template used when the quotation was issued. Those are different product requirements. A revised footer should not silently change the record of an already accepted quotation if your application promises historical copies.
For a final issued document, storing the generated PDF preserves that particular output. Storing only the layout and values allows regeneration, but it does not guarantee identical file bytes across SDK, font or rendering changes. Keep the artifact itself when your workflow requires the original file.
Distinguish schema versions from template revisions
The layout's schemaVersion identifies the SDK's JSON format. It is not a counter for every customer edit.
Your application can wrap the layout in its own revision metadata:
const templateRevision = {
templateId: 'quotation-standard',
revision: 3,
createdAt: new Date().toISOString(),
layout: editor.getStructure()
}
Save that wrapper through your application's persistence layer. Pass templateRevision.layout, rather than the entire wrapper, to generatePDF or downloadPDF.
The application should assign revision numbers and handle concurrent saves. Two authors can open revision 3 and both attempt to save changes. A version check in your persistence layer can reject a stale save and let the author reload or reconcile it. The PDF editor does not implement multi-user conflict resolution for your database.
Let pagination follow the data
A template may fit three services on one page and need several pages for a larger quotation. Forma PDF calculates continuation pages for text and tables, with repeated table headers.
Persist the original layout returned by getStructure(). Calculated continuation pages belong to a particular rendering; saving them as additional manual template pages would mix template design with record-specific output.
You can inspect calculated pages without opening the editor:
import { getTemplate, resolveDocument } from '/sdk/forma-pdf.js'
const template = getTemplate('quotation')
const longValues = {
...template.values,
items: Array.from({ length: 60 }, (_, index) => ({
service: `Example service ${index + 1}`,
quantity: '1',
price: '$10.00'
})),
quote: {
...template.values.quote,
total: '$600.00'
}
}
const shortDocument = await resolveDocument(
template.layout,
template.values
)
const longDocument = await resolveDocument(template.layout, longValues)
console.table({
short: { pages: shortDocument.pages.length },
long: { pages: longDocument.pages.length }
})
This example uses fictional services to exercise a growing table. Do not hard-code an expected page count: layout dimensions, font settings and content length influence the result.
The useful behavior to verify is that the longer record can expand, and a later short record recalculates from the original layout. Continuation pages should not accumulate as permanent additions to the template.
Automatic pagination is enabled by default. Fixed-box configurations have different overflow behavior, so use the same settings during testing that you intend to ship.
Before integrating a document workflow, check:
- A long table, followed by a short record using the same layout.
- Zero, false and empty-string values in fields that support them.
- A single table cell containing unusually long text.
- The generated file in a PDF reader, including branding and page breaks.
Choose the right output for the next step
The SDK provides three output functions for different application flows:
| Function | Result | Typical use |
|---|---|---|
downloadPDF(layout, values, filename) |
Promise<Blob> and a requested browser download |
User clicks a download button |
generatePDF(layout, values) |
Promise<Blob> |
Previewing or uploading the generated file |
generateBase64(layout, values) |
Promise<string> |
Integrating with an interface that explicitly requires base64 |
Base64 output is the encoded content without a data-URL prefix. Use it when the receiving interface expects that format; a Blob is usually more convenient for file-oriented browser APIs.
For a preview, create an object URL from the Blob and assign it to a viewer or link. Keep that URL alive while the preview needs it and revoke it when the preview closes or is replaced. An object URL is temporary browser state, not a permanent URL you can email to a customer.
For storage, upload the Blob through your application's authorized upload flow and store the resulting file identifier. The SDK does not provide an upload endpoint, email delivery or a hosted document archive.
Also distinguish “download requested” from “file saved.” Starting a browser download does not tell your application where the user saved it or whether they canceled it.
Integrate with a component-based frontend
The examples use plain JavaScript so the document flow is visible without framework-specific setup. In a component-based app, the same responsibilities still apply.
Mount the editor after its DOM container exists, retain the instance and destroy it during cleanup. Avoid recreating the entire editor on every unrelated component render. Load a saved document through the instance methods when appropriate, rather than rebuilding it just to replace its values.
For server-rendered applications, initialize the DOM editor in the browser. Treat this article's PDF generation path as client-side code too; it is not an example of a background server rendering service.
There is no requirement to mount an editor on the customer download route. That route can load the authorized layout and data, show a normal application form and call generatePDF or downloadPDF when the user is ready.
Understand where this workflow fits
This approach fits applications that need controlled, reusable document layouts and a visual authoring experience. Service quotations are one example: the document design can remain stable while customers, line items and terms change for each record.
The underlying template supports text, embedded PNG/JPEG images, lines and tables. It is not an HTML-to-PDF converter, so copying your application's HTML into the layout is not the integration model.
Similarly, generating a PDF from this template does not create an interactive PDF form or add a digital-signature workflow. If those are requirements, plan the corresponding tools and steps separately.
Browser execution also means large documents consume the user's device resources. Test representative documents on the devices your customers use. A successful small sample does not establish acceptable performance for every document size.
Keep application responsibilities explicit
Generation from a saved template runs in the browser and requires no AI key. Optional AI-assisted template creation is a separate workflow through a configured gateway.
Your host app remains responsible for authentication, record access, calculations, persistence and document delivery. A browser-side PDF library does not enforce who can access the underlying data.
The PDF generation core does not automatically upload document content or send telemetry. Any external transfer introduced by your own storage, analytics or optional AI integration should be assessed as part of that separate application workflow.
If you enable AI-assisted template creation, send that request through the configured gateway and review the result before applying it. Keep shared provider credentials on your backend. Generating subsequent PDFs from an approved saved layout does not require another AI request.
Try the workflow with your own document
Start with one document your application already produces. Identify which parts are layout decisions and which parts come from a record. Build a small values adapter, test a short and a long record, and decide where template revisions and final files belong in your application.
That gives you a concrete integration to evaluate: an author can change the template, a customer can use the application's ordinary screen, and the generator combines the selected layout with the current record.
You can explore the playground and API reference. The JavaScript SDK costs US$199 as a one-time license for one production application; the Bubble plugin is licensed separately.
Top comments (0)