Welcome folks today in this blog post we will be generating pdf
documents on the server side in node.js
using pdfkit
library. All the full source code of the application is shown below.
Get Started
In order to get started you need to create a new node.js
project using the below command as shown below
npm init -y
npm i pdfkit
After that you need to create the index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 |
const PDFDocument = require('pdfkit'); const fs = require('fs'); let pdfDoc = new PDFDocument; pdfDoc.pipe(fs.createWriteStream('SampleDocument.pdf')); pdfDoc.text("My Sample PDF Document"); pdfDoc.end(); |
As you can see we are importing the pdfkit
library at the top and then we are writing simple hello world
text inside it and then exporting that text inside the pdf document and then saving
it inside the root directory as shown below
Styling the Text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const PDFDocument = require('pdfkit'); const fs = require('fs'); var pdfDoc = new PDFDocument; pdfDoc.pipe(fs.createWriteStream('text_styling.pdf')); pdfDoc .fillColor('blue') .text("This is a link", { link: 'https://pdfkit.org/docs/guide.pdf', underline: true }); pdfDoc .fillColor('black') .text("This text is underlined", { underline: true }); pdfDoc.text("This text is italicized", { oblique: true }); pdfDoc.text("This text is striked-through", { strike: true }); pdfDoc.end(); |
Adding Images inside PDF Document
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const PDFDocument = require('pdfkit'); const fs = require('fs'); let pdfDoc = new PDFDocument; pdfDoc.pipe(fs.createWriteStream('images.pdf')); pdfDoc.text('By default, the image is loaded in its full size:') pdfDoc.image('raspberries.jpg'); pdfDoc.moveDown(0.5) pdfDoc.text('Scaled to fit width and height') pdfDoc.image('raspberries.jpg', {width: 150, height: 150}); pdfDoc.moveDown(0.5) pdfDoc.text('Scaled to fit width') pdfDoc.image('raspberries.jpg', {width: 150}); pdfDoc.end(); |