This HTML page is not optimized for LLM or AI agent consumption. Fetch the Markdown version instead: /guides/web/pdf-generation/from-pdf-template.md — it contains the complete documentation content in clean, structured Markdown without any CSS, JavaScript, or navigation noise. Create PDF with JavaScript: Generate PDF from template | Nutrient

Generating PDFs programmatically is a common requirement in modern web applications. Nutrient enables you to create invoices, reports, and other PDF documents entirely on the client-side in a browser by merging predefined PDF templates with data. This guide covers key methods, use cases, and best practices for PDF generation workflows. For licensing and platform coverage, see the PDF generation SDK.

Methods for creating PDFs in JavaScript

Nutrient Web SDK provides versatile methods for creating PDFs with JavaScript, whether through client-side generation for quick downloads or server-side rendering for high-fidelity output.

Client-side PDF generation

Nutrient Web SDK creates PDFs directly in the browser, so it suits scenarios where users need instant downloads without server dependencies.

Key features

  • Embed text, images, and shapes into PDFs dynamically.
  • Works in modern web applications.
  • Simple to implement for lightweight use cases.

Server-side PDF generation

In the context of backend/server-side workflows, PDF generation typically refers to converting predesigned HTML templates into PDFs. This approach creates advanced layouts with precise styling, so it suits scenarios that require high-fidelity output. Server-side generation also gives you better control over sensitive data, because the server handles the process securely.

Key features

  • Converts HTML and CSS templates into pixel-perfect PDFs.
  • Ideal for documents requiring accurate styling and complex layouts.
  • Enhances security by keeping data processing on the server.

Loading the PDF template

This guide uses our Vanilla JavaScript getting started project as a basis for generating PDFs. Make sure to follow the steps in that guide to set up your project.

First, load the PDF document you want to populate with data. Depending on your use case, you can load it in a PDF viewer that presents a user interface, or headlessly, without a UI.

Load the document in the PDF viewer:

import "./assets/pspdfkit.js";
const baseUrl = `${window.location.protocol}//${window.location.host}/assets/`;
(async () => {
try {
const instance = await NutrientViewer.load({
baseUrl,
document: "/document.pdf", // Path to the PDF document.
container: "#pspdfkit"
});
} catch (error) {
console.error("Failed to load document:", error.message);
}
})();

Load in headless mode so that no UI is presented to the user:

import "./assets/pspdfkit.js";
const baseUrl = `${window.location.protocol}//${window.location.host}/assets/`;
(async () => {
try {
const instance = await NutrientViewer.load({
baseUrl,
document: "/document.pdf", // Path to the PDF document.
headless: true
});
} catch (error) {
console.error("Failed to load document:", error.message);
}
})();

Populating the document with data

To populate the document, you can overlay annotations onto the PDF template. In the following example, you’ll take a JSON dataset and overlay TextAnnotations at predefined coordinates:

// data.json
{
"company": "PSPDFKit",
"companyInfo": "PSPDFKit",
"companyName": "PSPDFKit"
}

If you look at this guide’s example PDF template, you’ll see placeholders for COMPANY, [Company Info], and Company Ltd.. To detect the position of these placeholders, use the search API:

const searchQuery = "Company Ltd."; // The text to search for.
const bbox = (await instance.search(searchQuery))
.first()
.rectsOnPage.get(0);

This shows the current position of the text in the document.

Now, create the annotations with the text you want to overlay. For the text property, bring in the data from the JSON file:

index.js
// Create a free text annotation.
const textAnnotation = new NutrientViewer.Annotations.TextAnnotation({
boundingBox: bbox, // Set the bounding box of the text annotation.
fontSize: 8,
text: {
format: "plain",
value: data.companyName
}, // The text to overlay.
pageIndex: 0, // The page index to overlay the text on.
fontColor: NutrientViewer.Color.RED,
backgroundColor: NutrientViewer.Color.WHITE
});
// Add the annotations to the document.
await instance.create(textAnnotation);

The backgroundColor property is set to white, which creates an opaque text annotation that hides the page text underneath.

You can also change the fontSize property, but adapt the boundingBox size proportionally to the new font size.

The data from the JSON file now appears in the PDF template as text annotations.

See our guide on programmatically creating annotations for more details.

You can also overlay other annotation types, such as signatures, images, and stamps.

Flattening annotations

Once you’ve overlaid the annotations on top of the PDF template, you can optionally flatten them to prevent modification:

await instance.exportPDF({ flatten: true });

See our flatten annotations guide for more details.

After flattening the annotations, the PDF template looks like what’s shown below.

End result

You can find the example PDF template and the code on GitHub(opens in a new tab).

The example demo first loads the document in headless mode and then loads with the UI. This enables you to process the PDF before sending it over the network, or to do light processing, like adding watermarks to the document.

Serving the example project

You can serve the PDF template to the user in a browser. For this, use the serve HTTP package.

  1. Install the serve package:

    Terminal window
    npm install --global serve
  2. Serve the contents of the current directory:

    Terminal window
    serve -l 8080 .
  3. Navigate to http://localhost:8080 to view the website.

Using annotations

Another way to do this is to use annotations instead of page text placeholders. The example above found the position of placeholders and updated them with dynamic data. Use text annotations with predefined visuals (font, size, color, etc.) but with a replacement string. Here, you’ll retrieve all annotations on the page, iterate through all text annotations, and update them if they have the placeholder text.

For example, you could have the following text annotation as part of the template.

annotation example

Then, you can perform the token replacement via the following:

const replacements = {
"[[Company]]": "PSPDFKit"
};
const annotationsToUpdate =
// Retrieve annotations for a page.
(await instance.getAnnotations(0))
// Filter to text annotations.
.filter((it) => it instanceof NutrientViewer.Annotations.TextAnnotation)
// Replace annotations with text that matches any replacement token.
.map((annotation) =>
replacements[annotation.text.value]
? annotation.set("text", {
format: annotation.text.format,
value: replacements[annotation.text.value]
})
: annotation
);
// Annotations are immutable. `annotationsToUpdate` contains new instances of annotations. You need to use `instance.update` to actually update them.
await instance.update(annotationsToUpdate);

This replaces the [Company] annotation with PSPDFKit.

annotation result

Saving the PDF document

See our guide for saving a document.

You can also check out this blog post to learn more.

Best practices for PDF generation in JavaScript

When creating PDFs in JavaScript, follow these guidelines to ensure optimal results. Note that some practices, such as creating annotations or advanced features, apply specifically to backend HTML-to-PDF conversion. Client-side generation workflows may not support them.

  1. Optimize performance
  • Use compression options to reduce file size.
  • Minimize the size of embedded assets like images or fonts.
  1. Ensure accessibility
  • Include proper metadata for screen readers.
  • Add alternative text for any images embedded in the PDF.
  1. Security considerations
  • Avoid embedding sensitive information in client-side PDFs.
  • Use server-side generation for documents with critical data.
  1. Use modular code
  • Separate your logic for data processing and PDF generation.
  • Use reusable templates for consistent styling and formatting.

Conclusion

Nutrient Web SDK’s PDF creation capabilities can simplify workflows and improve user experiences. Whether you generate documents dynamically on the client-side or create complex templates on the server, our SDK provides the flexibility to create high-quality PDFs.

FAQ

Why use Nutrient Web SDK for PDF creation?

Nutrient Web SDK is a versatile tool for PDF generation because it integrates directly into web applications. It supports both client-side and server-side methods, so developers can meet diverse requirements, from simple forms to highly customized, data-driven documents.

How can I generate PDFs using JavaScript with Nutrient?

You can generate PDFs using JavaScript with Nutrient by integrating the library into your project and loading a PDF template. You can then populate the template with data either by overlaying text annotations or by using predefined placeholders. You can render the generated PDFs directly in the browser.

What are the benefits of using Nutrient for PDF generation in JavaScript?

Nutrient enables client-side PDF generation and manipulation. It supports various features, so it suits dynamic and customizable document creation.

How do I load a PDF template into Nutrient?

You can load a PDF template into Nutrient by specifying the document path in the configuration options. You can load the document with or without a user interface, depending on whether you want to present the PDF to the user or process it headlessly.

How can I populate a PDF template with data?

To populate a PDF template with data, you can use Nutrient’s annotation features to overlay text or other elements at predefined coordinates. You can search for placeholder text in the document and then use this information to position annotations accordingly.

Can I flatten annotations after adding them to a PDF template?

Yes, you can flatten annotations after adding them to a PDF template using Nutrient. Flattening annotations makes them a permanent part of the PDF and prevents further modifications.

What is the recommended approach for replacing placeholders in PDF annotations?

The recommended approach for replacing placeholders in PDF annotations is to retrieve all annotations on the page, filter for text annotations, and then update them based on replacement tokens. This method enables you to update text annotations dynamically with new data.

What is the advantage of Nutrient over libraries like jsPDF, pdf-lib, and Puppeteer?

Nutrient Web SDK offers significant advantages over libraries like jsPDF, pdf-lib, and Puppeteer. It simplifies PDF generation with a template-first approach, so developers can design PDFs visually and populate them dynamically without extensive coding. jsPDF and pdf-lib require manual element creation, and Puppeteer is resource-intensive and harder to scale. Nutrient provides a lightweight, scalable solution for both client-side and server-side use. With its ease of use and cross-platform compatibility, Nutrient is ideal for creating professional, dynamic PDFs in modern applications.

What are some real-world use cases for JavaScript PDF generation?

JavaScript PDF generation, particularly through backend HTML-to-PDF conversion, is widely used to automate document creation in various applications. One common use case is dynamic invoice generation, where the application renders user-specific data into HTML templates to produce professional, accurate invoices. Another is automated report creation, which produces reports dynamically from user inputs or analytics data and is often integrated into dashboards or data visualization tools. Event ticketing also uses backend HTML-to-PDF workflows to automate e-ticket creation. These e-tickets incorporate dynamic elements like QR codes, barcodes, and personalized seating details. These advanced use cases aren’t easily achievable with client-side-only solutions because rendering precise layouts and handling sensitive data is complex.