PDF Generation with Node JS

2016-05-17

Get started creating PDF file with Node and PDFKit.

Installation

1
$ npm install pdfkit --save

PDF Creation

Setup

Import the library and create the pdfKit document

index.js
1
2
3
4
5
6
7
8
9
10
11
12
var PDFDocument, doc;
var fs = require('fs');

PDFDocument = require('pdfkit');

doc = new PDFDocument;

doc.pipe(fs.createWriteStream('output.pdf'));

// PDF Creation logic goes here

doc.end();

Insert some text

index.js
1
2
3
4
5
6
7
8
// Set a title and pass the X and Y coordinates
doc.fontSize(15).text('Wally Gator !', 50, 50);

// Set the paragraph width and align direction
doc.text('Wally Gator is a swinging alligator in the swamp. He\'s the greatest percolator when he really starts to romp. There has never been a greater operator in the swamp. See ya later, Wally Gator.', {
width: 410,
align: 'left'
});

Check out the documentation for more options, including fonts, colors, text decorations and more !

Insert an image

index.js
1
doc.image('wally.jpg', 50, 150, {width: 300});

Result

Run the script as usual with

1
$ node index.js

And open the output.pdf file. You can check my result here. Once again, don’t forget to check out the official documentation for more examples and information.