Document Generation using PdfKit library

To start building documents using PdfKit library, we first need to install PdfKit package.

npm install pdfkit

The updated dependencies in package.json file will look like:

"dependencies": {
"express": "^4.18.2",
"pdfkit": "^0.14.0"
}

Example: Now, write the following code into the index.js file.

Javascript




// index.js
 
const express = require('express');
const PDFDocument = require('pdfkit');
 
const app = express();
const port = 3000;
app.use(express.json());
 
// Define a route for generating and serving PDF
app.post('/generate-pdf', (req, res) => {
    const { content } = req.body;
 
    const stream = res.writeHead(200, {
        'content-type': 'application/pdf',
        'content-disposition': 'attachment;filename=doc.pdf'
    });
 
    // Call the function to build the PDF, providing
    // callbacks for data and end events
    buildPdf(
        (chunk) => stream.write(chunk),
        () => stream.end()
    );
 
    // Function to build the PDF
    function buildPdf(dataCallback, endCallback) {
        const doc = new PDFDocument();
        doc.on('data', dataCallback);
        doc.on('end', endCallback);
        doc.fontSize(25).text(content);
        doc.end();
    }
});
 
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});


Step to run the application:

Step 1: Run the following command in the terminal to start the server.

node index.js

Step 2: Open the Postman app and make a post request with the following route and add the content in the body which you want to print on the pdf.

http://localhost:3000/generate-pdf
{
"content": "This is my first PDF generated with PdfKit"
}

Output:

How to generate document with Node.js or Express.js REST API?

Generating documents with Node and Express REST API is an important feature in the application development which is helpful in many use cases.

In this article, we will discuss two approaches to generating documents with Node.js or Express.js REST API.

Table of Content

  • Document Generation using PdfKit library
  • Document Generation using Puppeteer library

Similar Reads

Prerequisites:

Knowledge of NodeJS and ExpressJS API testing and Postman...

Setting up the Project and install dependencies.

Step 1: Create a directory for the project and move to that folder....

Approach 1: Document Generation using PdfKit library

To start building documents using PdfKit library, we first need to install PdfKit package....

Approach 2: Document Generation using Puppeteer library:

...

Contact Us