Node JS Create PDF From Images Example

Sep 09, 2022

.

Admin

Hi Dev,

Hello all! In this article, we will talk about node js create pdf from images example. We will use node.js to create pdf from images. This article goes into detail on nodejs create pdf from images. this example will help you create a pdf from images node.js. You just need to do some step to create a pdf from images nodejs.

I will give you a simple example of create a pdf from images in node js. 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-images, 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

//generate pdf file package

PDFDocument = require('pdfkit');

fs = require('fs');

doc = new PDFDocument

//Pipe its output somewhere, like to a file or HTTP response

doc.pipe(fs.createWriteStream('docPdf.pdf'))

//Add an image, constrain it to a given size, and center it vertically and horizontally

doc.image('img1.png', {

fit: [500, 400],

align: 'center',

valign: 'center'

});

doc.addPage()

.image('img2.png', {

fit: [500,400],

align: 'center',

valign: 'center'

});

doc.end()

Output:

I hope it can help you...

#Node JS