How to generate PDF files in Node.js

Generating PDF files is essential for Node.js applications that create invoices, reports, certificates, and downloadable documents. As the creator of CoreUI with over 11 years of Node.js development experience since 2014, I’ve built PDF generation features in countless enterprise applications. The most effective solution is to use PDFKit for programmatic PDF creation or Puppeteer for HTML-to-PDF conversion. This approach provides full control over document layout and formatting.

Use PDFKit to generate PDF files programmatically in Node.js.

const express = require('express')
const PDFDocument = require('pdfkit')
const fs = require('fs')

const app = express()

app.get('/generate-pdf', (req, res) => {
  const doc = new PDFDocument()

  // Set response headers
  res.setHeader('Content-Type', 'application/pdf')
  res.setHeader('Content-Disposition', 'attachment; filename=report.pdf')

  // Pipe PDF to response
  doc.pipe(res)

  // Add content
  doc
    .fontSize(25)
    .text('Monthly Report', 100, 100)

  doc
    .fontSize(12)
    .text('Generated on: ' + new Date().toLocaleDateString(), 100, 150)

  // Add table data
  doc.fontSize(14).text('Sales Summary', 100, 200)

  const data = [
    { product: 'Product A', sales: '$1,250' },
    { product: 'Product B', sales: '$2,340' },
    { product: 'Product C', sales: '$1,890' }
  ]

  let y = 230
  data.forEach(item => {
    doc.fontSize(12).text(`${item.product}: ${item.sales}`, 100, y)
    y += 20
  })

  // Add image
  doc.image('logo.png', 450, 100, { width: 100 })

  // Add page break
  doc.addPage()
  doc.fontSize(20).text('Page 2', 100, 100)

  // Finalize PDF
  doc.end()
})

First, install PDFKit with npm install pdfkit. Create a new PDFDocument instance and pipe it to the response stream. Use methods like text(), fontSize(), and image() to add content. The document builds incrementally as you call methods. Call end() to finalize the PDF. PDFKit supports advanced features like tables, forms, and vector graphics.

Best Practice Note

This is the same PDF generation approach we use in CoreUI backend systems for invoices and reports. For HTML-to-PDF conversion, use Puppeteer which renders HTML in a headless browser and exports to PDF, useful for complex layouts. Always stream PDFs directly to responses for large files rather than saving to disk first.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author