How to Create and Manipulate PDF Documents in Node.js with ‘PDFKit’ Module ?
Last Updated :
10 May, 2023
It is a very important and useful NPM package that can create and manipulate PDF documents. It can create simple and complex pdf documents which support texts, images, vector graphics, tables, etc. in the documents. This module can be used in creating invoices, reports, etc. which require complete control over formatting and layout.
Steps to create PDF documents in Node.js with ‘PDFKit’ module:
Installation: To use this package or module in your application, we have to install it first using the command given below. Give this command in the terminal and this module will get installed. After successful installation of the module, a JSON file will be added to the directory which contains all the details of the installed module.
$ npm install pdfkit
Installation
Use the Module: After successful installation, we can use this package in our JavaScript application. To use this package, we have to import it first using the require function and we also have to import ‘fs’ module because we are interacting with the pdf file. Then create a new pdf document using the createWriteStream( ) function by passing the pdf file name in it, then add content in it. You can add text by using fontSize and text methods. To add images we have to use the image method by passing the file name and properties of the image.
Javascript
const PDFDocument = require( "pdfkit" );
const fs = require( "fs" );
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream( "output.pdf" ));
doc.fillColor( "green" )
.fontSize(30)
.text( "GeeksforGeeks" );
doc.fillColor( "black" )
.fontSize(15)
.text( "It is the best platform for :- " );
doc.text( "Programming" );
doc.text( "Data Structures" );
doc.text( "Web development" );
doc.text( "Android development" );
doc.text( "Artificial intelligence, etc." );
doc.end();
|
Run the code: After successfully adding the content in the pdf file, we can run the javascript code using the command shown below. This will create a new pdf document having all the content described in the code.
$ node index.js
where index.js is the javascript file name.
Output:
output
Share your thoughts in the comments
Please Login to comment...