How to create PDF document in Node ?
Last Updated :
15 Jan, 2024
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
import PDFDocument from 'pdfkit'
import fs from 'fs'
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream( 'example.pdf' ));
doc
.fontSize(27)
.text( 'This the article for GeeksforGeeks' , 100, 100);
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);
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();
doc
.addPage()
.fillColor( 'blue' )
.text( 'The link for GeeksforGeeks website' , 100, 100)
doc.end();
|
Output: Created PDF file will look like this.
Share your thoughts in the comments
Please Login to comment...