Generating PDFs looks like a massive task when it comes to you at first, but with PDFKit it becomes a cake walk.
First of all, as we all know, we need to install the module through npm:
npm install pdfkit
Next, we make a generatePDFDocument.js file and write the following code in it:
var PDF = require('pdfkit'); var fs = require('fs');
var text = 'ANY_TEXT_YOU_WANT_TO_WRITE_IN_PDF_DOC';
doc = new PDF(); doc.pipe(fs.createWriteStream('PATH_TO_PDF_FILE')); doc.text(text, 100, 100); doc.end();
That's all the code we need to create a simple PDF document with text content. Now, we just need to run this using
node as follows:
And it should create a new PDF document at the path you provided in the code to the
writeStream. That's it folks, it took us only about 5 minutes to generate a PDF on server.
And There is a Lot More
There is a lot more that you can do with PDFKit, including Vector Graphics, Rich Text, Images, Annotations, etc.
For more information on the APIs and other examples, please refer to github.
We will be covering more about PDFs and use of PhantomJS (another powerful library) with Node.js in the coming posts.