Open In App

How to create PDF document in Node ?

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Creating PDF documents in Node.js is a versatile and powerful task, allowing developers to generate dynamic and professional-looking documents. This article provides a comprehensive guide on how to create PDF documents using Node.js.

Prerequisites:

Syntax:

const PDFDocument = require('pdfkit');
const doc = new PDFDocument;

Steps to create the application:

Step 1: Initialize the Node application

npm init -y

Step 2: Installing Module for setting NodeJS environment also we need to configure the package.json file and PDF module

npm install express pdfkit

For adding new page in the PDF.

doc.addPage()

For saving PDF document in root directory.

doc.pipe(fs.createWriteStream('PDF Name'));

Project Structure:

Folder Structure

The updated dependencies in package.json file will look like

"dependencies": {
"fs": "^0.0.1-security",
"pdfkit": "^0.11.0"
}

Explanation:

  • Initialization:
    • Import ‘PDFDocument’ and ‘fs’.
    • Create a new PDF document and set up a stream to save it.
  • Content Addition:
    • Add text, an image, and a new page with text and SVG path transformations.
  • Annotations and Finalization:
    • Add a page with blue text and a link to GeeksforGeeks.
    • Finalize and close the PDF file.
  • For adding new page in the PDF.
doc.addPage()
  • For saving PDF document in root directory.
doc.pipe(fs.createWriteStream('PDF Name'));

Example: Below is the practical implementation of the create PDF document in Node.js.

Javascript




// 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)
    .link(100, 100, 160, 27, 'https://www.geeksforgeeks.org/');
 
// Finalize PDF file
doc.end();


Output: Created PDF file will look like this.

Created PDF file



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads