65.9K
CodeProject is changing. Read more.
Home

Generating Server Side PDFs using PDFKit and Node.js

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (4 votes)

Apr 22, 2014

MIT

1 min read

viewsIcon

39080

downloadIcon

6

Generating server side PDFs in 5 minutes with PDFKit and Node.js

Nodejs PDF PDFkit

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');            //including the pdfkit module
var fs = require('fs');
var text = 'ANY_TEXT_YOU_WANT_TO_WRITE_IN_PDF_DOC';

doc = new PDF();                        //creating a new PDF object
doc.pipe(fs.createWriteStream('PATH_TO_PDF_FILE'));  //creating a write stream 
            //to write the content on the file system
doc.text(text, 100, 100);             //adding the text to be written, 
            // more things can be added here including new pages
doc.end(); //we end the document writing.

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.