Skip to content

Instantly share code, notes, and snippets.

@knoopx
Last active August 9, 2017 12:06
Show Gist options
  • Save knoopx/8d7fcfc8f2f556d4e4fb1b4bbd193034 to your computer and use it in GitHub Desktop.
Save knoopx/8d7fcfc8f2f556d4e4fb1b4bbd193034 to your computer and use it in GitHub Desktop.
chrome headless pdf generation
const fs = require('fs')
const CDP = require('chrome-remote-interface')
async function waitForNode(client, selector, waitTimeout) {
const { Runtime } = client
const getNode = selector => document.querySelector(selector)
const result = await Runtime.evaluate({
expression: `(${getNode})(\`${selector}\`)`,
})
if (result.result.value === null) {
const start = new Date().getTime()
return new Promise((resolve, reject) => {
const interval = setInterval(async () => {
if (new Date().getTime() - start > waitTimeout) {
clearInterval(interval)
reject(new Error(`wait("${selector}") timed out after ${waitTimeout}ms`))
}
const result = await Runtime.evaluate({
expression: `(${getNode})(\`${selector}\`)`,
})
if (result.result.value !== null) {
clearInterval(interval)
resolve()
}
}, 500)
})
}
}
async function run(url, file) {
const client = await CDP()
const { Network, Page } = client
await Promise.all([
Network.enable(),
Page.enable(),
])
await Page.navigate({ url })
await Page.loadEventFired()
await waitForNode(client, '.pdf', 1000)
const { data } = await Page.printToPDF({
paperWidth: 8.27,
paperHeight: 11.69,
marginTop: 0,
marginBottom: 0,
marginLeft: 0,
marginRight: 0,
})
fs.writeFileSync(file, Buffer.from(data, 'base64'))
await client.close()
}
run(process.argv[2], process.argv[3]).then(
() => { process.exit(0) },
(e) => {
console.error(e)
process.exit(-1)
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment