generate and download pdf file using node js

·

3 min read

Lets generate a PDF files this time

  1. install multiparty package in your application using npm install --save pdfkit command. This package is used to generate a pdf file.

  2. in your controller setup a route to serve a html page in which we will enter a file name and file content which we will add in pdf file. in my case this is my html file in which i will enter file name and file content. in your case you can add your content dynamically as per your requirements:

pdf-file-html.png

here are our html code:

pdf-html-code.png

and this is our code to generate and download PDF file:

generate-download-route-code.png

at the top of our route page we will have to import our pdfkit module so that we can use this module methods/features:

const PDFDocument = require('pdfkit');

our route name is pdf. in the first line we are creating an object of pdfDocument class. let filename = req.body.filename; in express JS every route have a req parameter which is request and using req.body we can get form controls in a key/value pair. so here i am getting filename input by user. in next lines are are adding .pdf extension in our file name and then passing headers. const content = req.body.content is used to get the content add by the user in our html form. now are are using PDFDocument() class object which is doc and by using this object we are assigning font size, text to pdf document. doc.fontSize(12) doc.text(content, 50, 50) doc.pipe(res) doc.end();

So this is the process to generate and download a pdf file in our node js application. If your pdf file requires more customization Please refer to the pdf kit documentation for more customization npmjs.com/package/pdfkit