
In this article, we will learn how we can generate PDF using nodejs.
To generate PDF we need a HTML page and using that page we will generate the same design in pdf. The HTML design would be a plateform to generate the PDF.
To create PDF you need to make HTML content of that particular, We will generate PDF of same HTML content.
So let's start generating PDF using node.js
I am using nodejs and I want to generate PDF on specific route ( end point/API ). It means I will hit that URL in my browser then it will generate the PDF and give us that pdf. we will use following npm modules:
ejs, fs and html-pdf
Create a package.json file and install the dependencies. you can take the reference of how you can create a package.json file from here
Install the above dependencies using npm:
npm install ejs fs html-pdf --save
Step 1: Create a server in nodejs:
Create a file with name "app.js" and paste the below code:
// app.js: Generate PDF using node.js
const express = require('express');
const app = express();
const utils = require('./pdfGenerator')
const port = 3100;
app.use(express.static(__dirname + '/'));
app.get('/', (req, res) => {
utils.createPdf()
.then((htmlString) => {
res.redirect("http://localhost:3100/mypdf.pdf");
});
});
app.listen(port, () => console.log(`App listening to port ${port}`));
Step 2: Write the HTML file to generate the pdf of that file:
Let's create a HTML file with name "example.html", and we will generate the pdf of html file later
Now create a file example.html in same directory and write the below code: