Introduction
Generating PDFs looks like a massive task when it comes to you at first, but with PDFKit it becomes a cake walk.
What's surprising is that not many people know about PDFKit module for Node.js. It makes dealing with PDF documents extremely easy. The module takes out all the complexities involved and provides simple APIs written in CoffeeScript which can also be used as plain JavaScript. In this post, we will be working towards generating a simple PDF document with text content on server side using PDFKit module and Node.js. So let's get started.
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:
node PATH_TO/generatePDFDocument.js
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.