Skip to content

Instantly share code, notes, and snippets.

@wych42
Last active December 10, 2017 10:08
Show Gist options
  • Save wych42/359eb8062831e57758a7c99e6aa6bcce to your computer and use it in GitHub Desktop.
Save wych42/359eb8062831e57758a7c99e6aa6bcce to your computer and use it in GitHub Desktop.
chrome headless print-to-pdf
'use strict';
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const [url, title] = process.argv.slice(-2,);
console.log('loading', title, url);
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// await page.emulate(devices['iPhone 6']);
await page.goto(url, {waitUntil: 'load'});
// page.pdf() is currently supported only in headless mode.
// @see https://bugs.chromium.org/p/chromium/issues/detail?id=753118
await page.setViewport({
width: await page.evaluate(() => document.body.clientWidth),
height: await page.evaluate(() => document.body.clientHeight)
});
await autoScroll(page);
await page.pdf({
path: './articles/' + title + '.pdf',
format: 'A4'
});
await browser.close();
})();
function autoScroll(page){
return page.evaluate(() => {
return new Promise((resolve, reject) => {
var totalHeight = 0;
var distance = 100;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if(totalHeight >= scrollHeight){
clearInterval(timer);
resolve();
}
}, 1000);
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment