08-Sep-2022
.
Admin
Hi Dev,
This tutorial will provide an example of how to create a pdf file in node.js. this example will help you how to generate a pdf file in nodejs. you can understand the concept of generate pdf file in node.js. we will help you to give example of generate a pdf file in nodejs.
I will give you a simple example of generate a pdf file in nodejs. we will use pdfkit npm package to create a pdf file.
PDFKit is a JavaScript PDF generation library for Node.js that provides an easy way to create multi-page, printable PDF documents.
So, let's start following example with output:
Step 1: Create Node.js Project
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
Step 2: Install pdfkit
This step is to install pdfkit package to generate a pdf file in your node app.
npm install pdfkit
Step 3: Update server.js file
server.js
const PDFGenerator = require('pdfkit')
const fs = require('fs')
// instantiate the library
let pdf = new PDFGenerator
// pipe to a writable stream which would save the result into the same directory
pdf.pipe(fs.createWriteStream('myPdf.pdf'))
// write text to your file
pdf.text('Hello Welcome to Nicesnippets.com')
// write out the file
pdf.end()
Output:
I hope it can help you...
#Node JS