Skip to content

Instantly share code, notes, and snippets.

@quangbuule
Created August 15, 2017 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quangbuule/4b781d581f203e59358111c075252d32 to your computer and use it in GitHub Desktop.
Save quangbuule/4b781d581f203e59358111c075252d32 to your computer and use it in GitHub Desktop.
Headless Chrome window size issue
const path = require('path');
const fs = require('fs');
const CDP = require('chrome-remote-interface');
function loadPage(client, url) {
const { Page } = client;
return Page.navigate({ url })
.then(Page.loadEventFired());
}
function printToPDF(client, url) {
const { Page } = client;
return loadPage(client, url)
.then(() => Page.printToPDF({
paperWidth: 10,
paperHeight: 10,
printBackground: true,
marginTop: 0,
marginBottom: 0,
marginLeft: 0,
marginRight: 0,
scale: 1
}));
}
function main() {
const url = `file://${path.join(__dirname, 'template.html')}`; // may be different on Windows
CDP(client =>
printToPDF(client, url)
.then(({ data }) => fs.writeFileSync('output.pdf', Buffer.from(data, 'base64')))
.then(
() => {
console.log("Printed to output.pdf");
client.close();
},
e => console.error(e.stack)
)
);
}
main();
{
"dependencies": {
"chrome-remote-interface": "^0.24.3"
}
}
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<style type="text/css">
html, body {
width: 100vw;
height: 100vh;
}
body {
color: gray;
}
@media(min-width: 7.5in) {
.test1 {
color: blue;
}
}
@media(min-width: 7.6in) {
.test2 {
color: blue;
}
}
@media(min-height: 5.6in) {
.test3 {
color: blue;
}
}
@media(min-height: 5.7in) {
.test4 {
color: blue;
}
}
@media(min-width: 720px) {
.test5 {
color: blue;
}
}
@media(min-width: 721px) {
.test6 {
color: blue;
}
}
@media(min-height: 539px) {
.test7 {
color: blue;
}
}
@media(min-height: 540px) {
.test8 {
color: blue;
}
}
</style>
</head>
<body>
<p>
Printing with paper size: 10 inch x 10 inch
</p>
<div class="test1">
min-width: 7.5in
</div>
<div class="test2">
min-width: 7.6in
</div>
<div class="test3">
min-height: 5.6in
</div>
<div class="test4">
min-height: 5.7in
</div>
<div class="test5">
min-width: 720px
</div>
<div class="test6">
min-width: 721px
</div>
<div class="test7">
min-height: 539px
</div>
<div class="test8">
min-height: 540px
</div>
</body>
</html>
@quangbuule
Copy link
Author

quangbuule commented Aug 15, 2017

npm i && node main

Chrome headless must be running when running this script, on MacOS:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --headless --disable-gpu --remote-debugging-port=9222

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