When working with Node JS, you often have the requirements to print PDF Documents. There are many npm packages available but unfortunately, many of them are useless. The library that works on the front end and back end is jsPDF. This library gives you a lot of options to format documents and insert images very easily.
How to use JSPDF in Node JS
First, you need to install jsPDF packages with npm or yarn. Run one of the following commands to install the package in your project.
1 2 3 4 5 6 7 |
npm install jspdf --save # or yarn add jspdf |
The above command will install the package in your project.
Printing a Simple Document with jsPDF
Now, let’s use the package to simply print a document with a text line. The following code snippets require the library in the first line and the next couple of lines are used to print the document on your machine.
1 2 3 4 5 6 7 8 9 10 |
const { jsPDF } = require("jspdf"); const pdfDocument = new jsPDF(); pdfDocument.text("This is a simple text", 10, 10); pdfDocument.save("example.pdf"); |
Changing the Orientation of PDF Document
By default, the options for the document are a4 paper with portrait type. You can change the options by passing an object when initializing the jsPDF. The following example changes the default options and set the page to landscape.
1 2 3 4 5 6 7 8 9 10 11 12 |
const { jsPDF } = require("jspdf"); const pdfDocument = new jsPDF({ orientation: "landscape", }); pdfDocument.text("This is a simple text", 10, 10); pdfDocument.save("example.pdf"); |
Adding Image to PDF with Node JS
You can add images to the PDF document but before that, you need to convert the image to base64. There are many packages that can do the job of converting an image to a base64 string on npm like node-base64-image. The following code example adds an image to the document and saves it as a PDF file.
1 2 3 4 5 6 7 8 9 10 11 |
const { jsPDF } = require("jspdf"); const pdfDocument = new jsPDF({ orientation: "landscape", }); pdfDocument.text("This is a simple text with image", 10, 10); pdfDocument.addImage(base64String,"PNG",15,40,180,160); pdfDocument.save("example.pdf"); |
You can read more about addImage
method on the official docs of jsPDF.
Conclusion
Creating a PDF file with node js is very easy if you are using jsPDF package. You can add text, images, and many more elements in PDFs. The library allows you to specify different options to style the document, and use custom fonts.