Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import puppeteer from 'puppeteer'
const browser = await puppeteer.launch({
args: [
'--no-sandbox'
],
timeout: 10000
})
const page = await browser.newPage()
const pageCookies = Object.entries(req.cookies || {}).map(cookie => {
return {
name: cookie[0],
value: cookie[1],
domain: 'localhost',
expires: Date.now() / 1000 + 10,
}
})
const pageParams = (new URLSearchParams({
name: req.body.name,
date: req.body.date,
duration: req.body.duration,
text: req.body.text,
city: req.body.city
})).toString() // query string
const fileName = md5(pageParams)
try {
await page.setViewport({ width: 850, height: 600 }) // resize view port of the browser
await page.setCookie(...pageCookies) // set cookies
await page.goto(`http://localhost:3000/admin/certificates/generate/preview?${pageParams}`) // go to url, with query string
// wait Vue element by ready
// it is not good using page.waitForNavigation() or
// page.waitForNavigation({ milliseconds , waitUntil: 'load|domcontentloaded' }),
// because Vue can defer page loading and this may fail in some cases, even with timeout
// it is better wait until you can get a css selector from loaded content.
await page.waitForSelector('.certificate .page')
// save pdf from the page
await page.pdf({
path: path.join(__dirname, `../../temp/${fileName}.pdf`),
width: '850px',
height: '600px',
printBackground: true,
pageRanges: '1'
})
// clear cookies and close instances.
// TODO: clear cookies seems redundant
await page._client.send('Network.clearBrowserCookies')
await page.close()
await browser.close()
response.file = `${fileName}.pdf`
} catch (err) {
console.error(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.