Creating a pdf with text and image in NodeJS
Posted By : RAJAT KATIYAR | 19-Jun-2016
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.