How to generate a PDF using Puppeteer
In this article, we will learn how to generate a PDF using Puppeteer. - 7/24/2024
2 min read
Introduction
In this article, we will learn how to generate a PDF using Puppeteer.
Use case
At the company where I work, we need to generate reports for our clients with some data about our product Onboarding, initially, we were using the lib the jsPDF which it worked fine at the beginning, but since we were adding more data, it started to be hard to manage the data and the style of the PDF report, so we decide to try out the Puppeteer to generate the PDF based on the HTML with the data and style.
Prerequisites
Before we start, make sure you have Node.js installed on your machine. You can download it from the official website here.
Setting up the project
First, create a new directory and navigate into it:
mkdir puppeteer-pdf
cd puppeteer-pdf
Next, initialize a new Node.js project:
npm init -y
Now, install Puppeteer:
npm i puppeteer
Generating a PDF
Create a new file called index.js
and add the following code:
const { writeFileSync } = require('fs')
const puppeteer = require('puppeteer')
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>This is an example PDF generated using Puppeteer.</p>
</body>
</html>
`
;(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setContent(html, { waitUntil: 'networkidle0' })
const pdf = await page.pdf({ format: 'A4', printBackground: true })
await browser.close()
writeFileSync('example.pdf', pdf)
})()
This code will open a new browser instance, create a new page, set the HTML content, and generate a PDF file called example.pdf
with the content of the HTML.
To run the script, execute the following command:
node index.js
After running the script, you should see a new file called example.pdf
in the project directory.
Conclusion
In this article, we learned how to generate a PDF using Puppeteer. Puppeteer is a powerful tool that allows you to automate tasks in the browser, such as generating PDFs, taking screenshots, and scraping websites.
I hope you found this article helpful. If you have any questions or feedback, feel free to reach out in the comments below.
Thank you for reading!