Skip to content

Instantly share code, notes, and snippets.

@itsdonnix
Last active November 26, 2023 11:50
Show Gist options
  • Save itsdonnix/a9fdf254f75c729ff4fdcb921325678c to your computer and use it in GitHub Desktop.
Save itsdonnix/a9fdf254f75c729ff4fdcb921325678c to your computer and use it in GitHub Desktop.
Generate PDF on NodeJS with Puppeteer & EJS
const ejs = require('ejs')
const puppeteer = require('puppeteer')
const fs = require('fs')
const { Buffer } = require('buffer')
const { PDFDocument } = require('pdf-lib')
async function createPDF({ template, data, output, title = 'Laporan', format = 'A4' }) {
const content = ejs.render(fs.readFileSync(template).toString(), data)
const browser = await puppeteer.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-3d-apis',
'--disable-web-security',
'--font-render-hinting=none',
],
})
const page = await browser.newPage()
await page.goto('data:text/html,' + content, { waitUntil: 'networkidle0' })
let pdf = await page.pdf({
format,
path: output || null,
margin: {
top: '20px',
bottom: '20px',
left: '20px',
right: '20px',
},
})
browser.close()
// Set the title
pdfdoc = await PDFDocument.load(pdf)
pdfdoc.setTitle(title)
pdf = await pdfdoc.save()
return Buffer.from(pdf)
}
// Use
const pdf = await createPDF({
template: path.resolve(__dirname, 'templates', 'template.ejs'),
title: "My PDF Title",
data: { name: 'John Doe', age: 34 },
})
@WisaniShilumani
Copy link

This is cool! What's the purpose of the template.ejs? Are you writing a blog, been wanting to createPDFs on my server

@itsdonnix
Copy link
Author

itsdonnix commented Jan 29, 2021

Thank's @WisaniShilumani, No, I just want to generate some complex data report with pdf format (also with some merge cells)... and I think the cleaner way is to using template engine like EJS. BTW I try jsPDF before, but its hard to create table especially when centering things. The only advantage is it can be run on browser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment