In this article, we will learn how to convert HTML to PDF.
–First of all, create a project and install npm i express module.
–Then add a server.js file and add the below code there.
const express = require('express') const app = express() const port = 5000 app.use(express.json()) app.listen(port, () => console.log(`Example app listening on port ${port}!`))
–Create a pdf folder in the root directory.
— Then install npm i html-pdf-node module and add the below code in server.js file.
- html-pdf-node plugin use for convert HTML to PDF file
app.get('/pdfconvert', (req, res) => { const html_to_pdf = require('html-pdf-node'); const options = { format: 'A4', path: './pdf/convert.pdf' }; let file = { content: "<h1>HTML to PDF convert</h1>" }; html_to_pdf.generatePdf(file, options) .then((re) => { res.status(200).send({ isSuccess: true, }) }).catch((err) => { res.status(200).send({ isSuccess: false, error:err }) }); })
–Test the pdfconvert API
http://localhost:5000/pdfconvert
–PDF file created