Generate a PDF file using Puppeteer in Node js
In this article, We will explain to you how to generate a pdf file using puppeteer in node.js. normally puppeteer is a node library and it is developed by Google.
Now, we will install the puppeteer npm in the application and it used to we can easily create the pdf file. so you can follow the below command for the install puppeteer.
1 | npm install puppeteer |
Here in this article, we have created a simple application so you can understand.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | const express = require('express'); const app = express(); const port = 3000; const puppeteer = require ('puppeteer'); app.get("/html2pdf", (req, res, next) => { var html ='<h2>XpertPhp</h2>'; (async function () { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setContent (html); await page.emulateMedia ('screen'); const pdf = await page.pdf({ format: 'A4',printBackground: true }); res.set({ 'Content-Type': 'application/pdf', 'Content-Length': pdf.length }); res.send(pdf); }catch (e) { console.log ('our error', e); } })() ; }); app.listen(port, () => console.log(`Example app listening on port ${port}!`)) |
If you want to the download pdf file in your directory then you can use the below code.
1 2 3 4 5 6 7 8 | await page.pdf ({ //name of your pdf file in directory path: 'testpdf.pdf', format: 'A4', printBackground: true }); await browser.close(); process.exit(); |
Finally, you can run the application follow the below URL.
1 | http://localhost:3000/html2pdf |
Please follow and like us: