Alter the default header/footer when printing to PDF
This is an update/answer to the question. As of Chromium 64 it is possible using the headerTemplate
and footerTemplate
parameters to printToPDF
Using chrome remote interface here's example code that should work:
return new Promise(async function (resolve, reject) {
const url = "<MyURL here>";
const [tab] = await Cdp.List()
const client = await Cdp({ host: '127.0.0.1', target: tab });
await Promise.all([
Network.enable(),
Page.enable()
]);
Page.loadEventFired(function () {
setTimeout(function () {
//https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF
resolve(Page.printToPDF({
displayHeaderFooter:true,
footerTemplate: "<span class='pageNumber'> of <span class='totalPages'>"
})));
}, 3000);
});
await Page.navigate({ url });
};
There are two solutions to your problem
A) Push the chrome-header out by leaving no margin :
@page {
margin: 0;
size: auto;
}
or
@media print {
@page { margin: 0; }
body { margin: 1.6cm; }
}
B) Originally a Firefox solution which should world for Chrome
<html moznomarginboxes mozdisallowselectionprint>
some sample:
<!DOCTYPE html>
<html moznomarginboxes mozdisallowselectionprint>
<head>
<title>Print PDF without header</title>
<style>
@media print {
@page { margin: 0; }
body { margin: 1.6cm; }
}
</style>
</head>
<body>
<p>Some Text in Paragraph to print!</p>
<a href="javascript:print()">Print</a>
</body>
</html>
It is possible to create custom headers and footer by using <header>
and <footer>
tags. I use this for generating PDF's using Chrome Headless. I have not tested it in Firefox, IE etc...
<header>
Custom Header
<img src="http://imageurl.com/image.jpg"/>
</header>
<div class="content">Page Content - as long as you want</div>
<footer>
Footer Content
</footer>
the CSS
@page {
margin: 0;
}
@media print {
footer {
position: fixed;
bottom: 0;
}
header {
position: fixed;
top: 0;
}
}
The @page { margin: 0 }
removes the default header and footer.
Hope this helps.