Skip to content

Instantly share code, notes, and snippets.

@tomshaw
Created January 16, 2020 21:14
Show Gist options
  • Save tomshaw/5071a3669428f27bbb6c63d8ec14de58 to your computer and use it in GitHub Desktop.
Save tomshaw/5071a3669428f27bbb6c63d8ec14de58 to your computer and use it in GitHub Desktop.
Quickly export to PDF whatever page/url.
#!/usr/bin/env node
const puppeteer = require('puppeteer');
/**
* npm link/savepage url=https://stackoverflow.com/
* Margins default to Microsoft Word A4 margins.
*/
class SavePage {
constructor(params) {
const settings = this.normalizeOptions(params);
if (!settings.url) {
throw new Error('Missing save page url! Try again.');
}
const config = {
verbose: true,
consolePage: false,
consoleOptions: false,
path: `${this.getHostName(settings.url)}.pdf`,
width: 800,
height: 600,
waitUntil: 'networkidle2',
headless: true,
slowMo: 0, // 250ms
deviceScaleFactor: 1,
format: 'A4',
printBackground: false,
margin: {
top: '2.54cm',
bottom: '2.54cm',
left: '2.54cm',
right: '2.54cm'
}
};
this.options = { ...config, ...settings };
}
async save() {
const options = this.options;
if (options.consoleOptions === true) {
console.log('Save options:', options);
}
const browser = await puppeteer.launch({
headless: options.headless,
slowMo: options.slowMo
});
const page = await browser.newPage();
await page.setViewport({
width: options.width,
height: options.height,
deviceScaleFactor: options.deviceScaleFactor
});
await page.goto(options.url, { waitUntil: options.waitUntil });
if (options.verbose === true) {
const data = await page.evaluate(() => {
return {
href: location.href,
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio
};
});
console.log('...');
console.log('URL:', data.href);
console.log('Page width:', data.width);
console.log('Page height:', data.height);
console.log('Page scale:', data.deviceScaleFactor);
}
if (options.consolePage) {
page.on('console', msg => console.log(msg.text()));
}
await page.pdf({
path: options.path,
format: options.format,
printBackground: options.printBackground,
margin: options.margin
});
return await browser.close();
}
normalizeOptions(args) {
return args
.slice(2)
.map(arg => arg.split('='))
.reduce((args, [value, key]) => {
args[value] = key;
return args;
}, {});
}
getHostName (url) {
return new URL(url).hostname;
}
}
(async () => {
const page = new SavePage(process.argv);
await page.save();
})();
@tomshaw
Copy link
Author

tomshaw commented Jan 16, 2020

{
"name": "savepage",
"version": "1.0.0",
"description": "",
"main": "savepage.js",
"bin": {
"savepage": "savepage.js"
},
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "Tom Shaw tomshaw21@gmail.com (http://tomshaw.us)",
"license": "ISC",
"dependencies": {
"puppeteer": "^2.0.0"
},
"devDependencies": {}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment