You are currently viewing Generating PDF Documents in Node.js using PDFKit

Generating PDF Documents in Node.js using PDFKit

  • Post author:
  • Post category:Nodejs
  • Post comments:0 Comments
  • Post last modified:May 3, 2024

Introduction

In this tutorial, we’ll explore how to generate PDF documents dynamically in Node.js using PDFKit. PDFKit is a popular library that allows you to create and manipulate PDF documents easily. By the end of this tutorial, you’ll be able to create custom PDFs with text, images, tables, and more.

Prerequisites

Before we get started, ensure you have the following installed:

  • Node.js and npm (Node Package Manager) installed on your machine.

Getting Started

Step 1: Initialize a Node.js Project

First, let’s create a new directory for our project and initialize a new Node.js project. Open your terminal and run the following commands:

mkdir pdfkit-example
cd pdfkit-example
npm init -y

Step 2: Install PDFKit

Next, let’s install PDFKit as a dependency for our project:

npm install pdfkit

Step 3: Create a PDF Document

Now, let’s create a simple Node.js script to generate a PDF document using PDFKit. Create a file named generatePDF.js in your project directory and add the following code:

This script creates a simple PDF document with the text “Hello, PDFKit!” centered at the top.

Step 4: Run the Script

To generate the PDF document, run the following command in your terminal:

node generatePDF.js

This will create a file named example.pdf in your project directory containing the generated PDF.

Advanced Usage

Now that you have a basic understanding of how to generate PDFs using PDFKit, let’s explore some more advanced features:

Adding Text with Formatting

// Add formatted text to the PDF
doc
  .fontSize(18)
  .text('This is a paragraph of text.', { width: 410, align: 'left' });

Adding Images

const imagePath = 'path/to/image.jpg';

// Add an image to the PDF
doc.image(imagePath, { width: 200 });

Adding Tables

// Add a table to the PDF
const tableData = [
  ['Name', 'Age', 'Country'],
  ['John Doe', 30, 'USA'],
  ['Jane Smith', 25, 'UK']
];

doc.table(tableData, {
  width: 300,
  prepareHeader: () => doc.font('Helvetica-Bold'),
  prepareRow: (row, i) => doc.font('Helvetica').fontSize(12)
});

Adding Custom Styles

// Add custom styles to the PDF
doc
  .font('Helvetica-Bold')
  .fontSize(24)
  .text('Custom Styles', { align: 'center' });

Conclusion

In this tutorial, you learned how to generate PDF documents dynamically in Node.js using PDFKit. You can now create custom PDFs with text, images, tables, and more. PDFKit offers extensive functionality for creating professional-quality PDF documents programmatically, making it a powerful tool for generating reports, invoices, and other types of documents in Node.js applications.

For more information and advanced usage, refer to the PDFKit documentation.

Leave a Reply