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.

Revisions

  1. itsdonnix revised this gist Jan 29, 2021. No changes.
  2. itsdonnix created this gist Jan 29, 2021.
    49 changes: 49 additions & 0 deletions pdf.js
    Original 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 },
    })