Last active
November 26, 2023 11:50
-
-
Save itsdonnix/a9fdf254f75c729ff4fdcb921325678c to your computer and use it in GitHub Desktop.
Revisions
-
itsdonnix revised this gist
Jan 29, 2021 . No changes.There are no files selected for viewing
-
itsdonnix created this gist
Jan 29, 2021 .There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ 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 }, })