Generate PDFs from a Template Using JavaScript

With PSPDFKit, you can use templates to create a PDF, without needing an internet connection. This is useful for generating tickets where you may need to populate predesigned fields with text.

Setting Up the Page

First, you’ll need to load the document you wish to populate with the content. Load this in headless mode so that no UI is presented to the user:

const instance = await PSPDFKit.load({
  headless: true,
  document: document
});

Populating the Document

To populate the document, use TextAnnotations to overlay your dynamically generated text, like so:

// Create a free text annotation.
const textAnnotation = new PSPDFKit.TextAnnotation({
  boundingBox: new PSPDFKit.Geometry.Rect({
    left: 228,
    top: 924,
    width: 600,
    height: 80
  }),
  fontSize: 40,
  text: "Ticket #343534",
  pageIndex: 0
});

const textAnnotation2 = new PSPDFKit.TextAnnotation({
  boundingBox: new PSPDFKit.Geometry.Rect({
    left: 228,
    top: 924,
    width: 600,
    height: 80
  }),
  fontSize: 40,
  text: "Seat 45",
  pageIndex: 0
});

// Add the annotations to the document.
await instance.create([textAnnotation, textAnnotation2]);

See our guide on programmatically creating annotations for more details.

Flattening Annotations

Flattening annotations can be useful, as this prevents users from modifying the annotations. Using the sample code below, which requires the Document Editing license component, you can flatten all annotations:

await instance.applyOperations({
  type: "flattenAnnotations"
});

See our flatten annotations guide for more details.

We use cookies to improve your experience and for marketing. Learn more in our privacy policy.