Creating a pdf with text and image in NodeJS

Posted By : RAJAT KATIYAR | 19-Jun-2016

Creating a pdf with Text and Image in NodeJS

There are many ways, a pdf file can be created in nodejs. Here we have used pdf kit node module for creating the pdf. Before starting, please install the "pdfkit" module in the project. 

 

First of all, define all the variables required, 

 

var PDF = require('pdfkit');            //including the pdfkit module
var fs = require('fs');                 //including the file system module

var text = 'ANY_TEXT_YOU_WANT_TO_WRITE_IN_PDF_DOC';        //define a dummy text to be written in the file
var request = require('request');

 

Now create a PDF object which can be used to insert the data.

 

doc = new PDF();                        //creating a new PDF object

//creating a write stream to write the content on the file system


doc.pipe(fs.createWriteStream('/home/oodles/testing_file.pdf'));  
 

//Now this is the code snippet to get the image using the url

 

            request({
                url: 'http://localhost:8590/1464935924521.jpg',
                encoding: null // Prevents Request from converting response to string
              }, function(err, response, body) {
              if (err) throw err;

 

// Inject the image with the required attributes
 

              doc.image(body,260, 50,{height:100,width:100});
              doc.text('HOLIDAYS - 125 Fortime',80,165,{align:'center'})
              doc.text('Hello this is a demo file',100,200)
             

// Close document and, by extension, response

              doc.end(); 
              return;
    });

 

Running the above code will result in creation of a PDF file at the given path.

 

THANKS

About Author

Author Image
RAJAT KATIYAR

Rajat Katiyar is a very bright web app developer, he has good knowledge of JAVA, C/C++, C#.NET. Apart from this he has interest in theater and sports.

Request for Proposal

Name is required

Comment is required

Sending message..