How To Generate PDF File In Node JS Using PDFKit

In this article, we will see how to generate a pdf file in node js using pdfkit. Here, we will learn about the javascript PDF generation library for node js and the browser. For this article, we will use the PDFKit javascript library. You can use it in the node js as well as used in the browser.

So, let's see PDFKit HTML to PDF Node JS, PDFKit node js, PDFKit HTML to PDF javascript, node js generate PDF from HTML using PDFKit, and how to create PDF file using javascript.

PDFKit is a PDF document generation library for Node and the browser that makes creating complex, multi-page, printable documents easy. The PDFKit API is designed to be simple, so generating complex documents

Step 1: Create Node JS Project

 In this step, we will create pdfkit-example directory using the following command.

mkdir pdfkit-example
cd pdfkit-example

After that, we will initialize a new Node.js project in the folder.

npm init

 

Step 2: Install PDFKit

Now, we will install PDFKit using the npm package manager. Type the following command after installing npm.

npm install pdfkit

 

 

Step 3: Create index.js File

In this step, we will create an index.js file and add the below code to that file.

const PDFDocument = require('pdfkit');
const fs = require('fs');

// Create a document
const doc = new PDFDocument();

// Pipe its output somewhere, like to a file or HTTP response
// See below for browser usage
doc.pipe(fs.createWriteStream('output.pdf'));

// Embed a font, set the font size, and render some text
doc
  .font('fonts/PalatinoBold.ttf')
  .fontSize(25)
  .text('Some text with an embedded font!', 100, 100);

// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('path/to/image.png', {
  fit: [250, 300],
  align: 'center',
  valign: 'center'
});

// Add another page
doc
  .addPage()
  .fontSize(25)
  .text('Here is some vector graphics...', 100, 100);

// Draw a triangle
doc
  .save()
  .moveTo(100, 150)
  .lineTo(100, 250)
  .lineTo(200, 250)
  .fill('#FF3300');

// Apply some transforms and render an SVG path with the 'even-odd' fill rule
doc
  .scale(0.6)
  .translate(470, -380)
  .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
  .fill('red', 'even-odd')
  .restore();

// Add some text with annotations
doc
  .addPage()
  .fillColor('blue')
  .text('Here is a link!', 100, 100)
  .underline(100, 100, 160, 27, { color: '#0000FF' })
  .link(100, 100, 160, 27, 'http://google.com/');

// Finalize PDF file
doc.end();

 

Example: Using PDFKit in the browser

PDFKit can be used in the browser as well as in Node. There are two ways to use PDFKit in the browser. The first is to create an app using a module bundler like Browserify or Webpack.

// require dependencies
const PDFDocument = require('pdfkit');
const blobStream  = require('blob-stream');

// create a document the same way as above
const doc = new PDFDocument;

// pipe the document to a blob
const stream = doc.pipe(blobStream());

// add your content to the document here, as usual

// get a blob when you're done
doc.end();
stream.on('finish', function() {
  // get a blob you can do whatever you like with
  const blob = stream.toBlob('application/pdf');

  // or get a blob URL for display in the browser
  const url = stream.toBlobURL('application/pdf');
  iframe.src = url;
});

JS Files:

<script src="https://github.com/devongovett/pdfkit/releases/download/v0.10.0/pdfkit.standalone.js"></script>
<script src="https://github.com/devongovett/blob-stream/releases/download/v0.1.3/blob-stream.js"></script>

 

Options:

Text:

PDFKit makes adding text to documents quite simple

doc.text('Hello world!')

You can modify the position of the text by passing X and Y coordinates to the text method

doc.text('Hello world!', 150, 150)

Justification:

You can justify the content using the four options: left (the default), centerright, and justify

const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus.  Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl.';

doc.fontSize(8);
doc.text(`This text is left aligned. ${lorem}`, {
  width: 410,
  align: 'left'
}
);

doc.moveDown();
doc.text(`This text is centered. ${lorem}`, {
  width: 410,
  align: 'center'
}
);

doc.moveDown();
doc.text(`This text is right aligned. ${lorem}`, {
  width: 410,
  align: 'right'
}
);

Page Size:

PDFKit has a number of predefined page sizes.

// Passing size to the constructor
const doc = new PDFDocument({size: 'A4'});

// Passing size to the addPage function
doc.addPage({size: 'A4'});

Image:

Also, you can add images to the PDF file using the PDFKit. PDFKit supports JPEG and PNG formats.

// Scale proprotionally to the specified width
doc.image('images/test.jpeg', 0, 15, {width: 300})
   .text('Proportional to width', 0, 0);

// Fit the image within the dimensions
doc.image('images/test.jpeg', 320, 15, {fit: [100, 100]})
   .rect(320, 15, 100, 100)
   .stroke()
   .text('Fit', 320, 0);

// Stretch the image
doc.image('images/test.jpeg', 320, 145, {width: 200, height: 100})
   .text('Stretch', 320, 130);

// Scale the image
doc.image('images/test.jpeg', 320, 280, {scale: 0.25})
   .text('Scale', 320, 265);

// Fit the image in the dimensions, and center it both horizontally and vertically
doc.image('images/test.jpeg', 430, 15, {fit: [100, 100], align: 'center', valign: 'center'})
   .rect(430, 15, 100, 100).stroke()
   .text('Centered', 430, 0);

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS