Open In App

How to Create and Manipulate PDF Documents in Node.js with ‘PDFKit’ Module ?

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Importing required modules
const PDFDocument = require("pdfkit");
const fs = require("fs");
  
// Creating a new instance of PDFDocument class
const doc = new PDFDocument();
  
// Piping the output stream to a file
// named "output.pdf"
doc.pipe(fs.createWriteStream("output.pdf"));
  
// Setting the fill color to green and
// font size to 30
doc.fillColor("green")
    .fontSize(30)
    .text("GeeksforGeeks");
  
// Setting the fill color to black and
// font size to 15
doc.fillColor("black")
    .fontSize(15)
    .text("It is the best platform for :- ");
  
// Adding multiple lines of text to
// the document
doc.text("Programming");
doc.text("Data Structures");
doc.text("Web development");
doc.text("Android development");
doc.text("Artificial intelligence, etc.");
  
// Ending the document
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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads