Skip to content

Instantly share code, notes, and snippets.

@adisetiawan
Created August 29, 2017 07:23
Show Gist options
  • Save adisetiawan/29ba2bab10ed85706f8b1d1a8eceb825 to your computer and use it in GitHub Desktop.
Save adisetiawan/29ba2bab10ed85706f8b1d1a8eceb825 to your computer and use it in GitHub Desktop.
//npm init -y
//npm install --save puppeteer
//usage: node script.js /path/to/input.html /path/to/output.pdf
//script.js
const puppeteer = require('puppeteer');
(async () => {
let fileinput = process.argv[2];
let fileoutput = process.argv[3];
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('file:///${fileinput}', {waitUntil: 'networkidle'});
await page.pdf({path: fileoutput, format: 'A4'});
browser.close();
})();
@djm
Copy link

djm commented Jul 2, 2018

Thanks for this!

Just a note for anyone that might use this on a server: tread carefully as the fileInput here is not sanitised and thus, if it was set by a user, it could be set to /etc/passwd (for example) and that would render a screenshot of that file, possibly dangerously revealing its contents if the file was sent back to the user.

The safest way around this is to ensure the value is never used in user input; but if it must be, then ensure the file:/// prefix cannot be used.

@nylen
Copy link

nylen commented Sep 6, 2018

Good note, @djm. Another kind of user-entered URL to avoid is http://localhost:port or http://127.x.x.x:port or others with a similar meaning. This can have unintended consequences including discovering and manipulating any services that may be running locally on the server or its network.

An example of a function that handles validating URLs in this way: https://github.com/WordPress/wordpress-develop/blob/4.9.8/src/wp-includes/http.php#L506-L582

And then there are IPv6 addresses to account for too...

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