How to create PDF document in Node.js ?
In this article, we will see how to generate PDF documents in NodeJS.
Prerequisites:
- Basic knowledge of Node.js.
- Node.js installed (version 12+).
- npm installed (version 6+).
Step 1: Install PDF module. The PDFkit– It is an Inbuilt Module for generating the PDF documents in the NodeJS in a very simpler and easy way in which we can make graphics, load images and also provide link of the website.
- For installing it in the project write the following command on the terminal or command prompt.
npm install pdfkit
Syntax:
const PDFDocument = require('pdfkit'); const doc = new PDFDocument;
- For adding new page in the PDF.
doc.addPage()
- For saving PDF document in root directory.
doc.pipe(fs.createWriteStream('PDF Name'));
Step 2: Installing Module for setting NodeJS environment. Also we need to configure the package.json file.
npm install express
Filename: package.json
Javascript
{ "name" : "node_func" , "version" : "1.0.0" , "description" : "" , "main" : "index.js" , "scripts" : { "test" : "echo \"Error: no test specified\" && exit 1" , "start" : "node app.js" , "dev" : "nodemon app.js" }, "author" : "" , "license" : "ISC" , "dependencies" : { "fs" : "^0.0.1-security" , "pdfkit" : "^0.11.0" } } |
Folder Structure: We can see that the PDF file is created in root directory.

Folder Structure
Example: Here is the JavaScript code that should be written in app.js which is for NodeJS.
Filename: index.js
index.js
// Importing modules import PDFDocument from 'pdfkit' import fs from 'fs' // Create a document const doc = new PDFDocument(); // Saving the pdf file in root directory. doc.pipe(fs.createWriteStream( 'example.pdf' )); // Adding functionality doc .fontSize(27) .text( 'This the article for GeeksforGeeks' , 100, 100); // Adding an image in the pdf. doc.image( 'download3.jpg' , { fit: [300, 300], align: 'center' , valign: 'center' }); doc .addPage() .fontSize(15) .text( 'Generating PDF with the help of pdfkit' , 100, 100); // Apply some transforms and render an SVG path with the // 'even-odd' fill rule doc .scale(0.6) .translate(470, -380) .path( 'M 250,75 L 323,301 131,161 369,161 177,301 z' ) .fill( 'red' , 'even-odd' ) .restore(); // Add some text with annotations doc .addPage() .fillColor( 'blue' ) .text( 'The link for GeeksforGeeks website' , 100, 100) // Finalize PDF file doc.end(); |
Output: Created PDF file will look like this.
Please Login to comment...