HTML to PDF Converter with Puppeteer

4.0.1 · active · verified Sun Apr 19

pdf-creator-node is a Node.js library for converting HTML and Handlebars templates into PDF documents. It leverages Puppeteer, a headless Chromium browser, for rendering, ensuring support for modern CSS features like Flexbox, Grid, and web fonts. As of version 4.0.1, it has moved entirely to Puppeteer, replacing its prior reliance on PhantomJS/html-pdf. This change, introduced in v4.0.0, brings improved rendering fidelity and a more actively maintained underlying engine, though it comes with a larger install footprint due to Chromium. The library is actively maintained, as evidenced by recent v4.0.x releases, and provides a programmatic API to generate reports, invoices, and letters from templated HTML. It balances ease of use for HTML-centric document generation with the resource considerations inherent to a Chromium-based solution, suitable for small to medium-scale production workloads.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a PDF from an HTML and Handlebars template, including dynamic data, custom headers, and footers, saving it to a file, using ESM syntax.

import pdf from "pdf-creator-node";
import fs from "fs";
import path from "path";

const htmlTemplate = `
  <!DOCTYPE html>
  <html>
    <head>
      <style>
        body { font-family: sans-serif; margin: 20mm; }
        h1 { color: #333; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        .footer { position: fixed; bottom: 0; width: 100%; text-align: center; font-size: 10px; color: #666; }
      </style>
    </head>
    <body>
      <h1>User Report</h1>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
          </tr>
        </thead>
        <tbody>
          {{#each users}}
          <tr>
            <td>{{this.name}}</td>
            <td>{{this.age}}</td>
          </tr>
          {{/each}}
        </tbody>
      </table>
      <div class="footer">Page {{page}} of {{pages}}</div>
    </body>
  </html>
`;

const usersData = [
  { name: "Alice", age: 30 },
  { name: "Bob", age: 24 },
  { name: "Charlie", age: 35 }
];

const options = {
  format: "A4",
  orientation: "portrait",
  border: "10mm",
  header: { height: "15mm", contents: { default: '<h2 style="text-align: center;">PDF Report Header</h2>' } },
  footer: { height: "10mm", contents: { default: '<span style="color: #444;">{{page}}</span>/<span>{{pages}}</span>' } },
  path: path.join(process.cwd(), 'output.pdf') // Use path.join for cross-platform compatibility
};

const document = {
  html: htmlTemplate,
  data: { users: usersData },
  path: options.path,
};

pdf.create(document, options)
  .then((res) => console.log('PDF created:', res.filename))
  .catch((err) => console.error('Error creating PDF:', err));

view raw JSON →