I\'m trying to use Google Chrome as a replacement of PhantomJS to render HTML into PDF. So far it\'s been working well for me. The only issue I have that I have not found an
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.
You can use the headerTemplate
and footerTemaplate
parameters in printToPDF to customize the header and footer when printing to PDF.
headerTemplate
and footerTemaplate
accept valid HTML markup, and you can use the following classes to inject printing values into your HTML elements:
date
- will inject the current date in printable format into the HTML element containing the classtitle
- document titleurl
- document locationpageNumber
- current page numbertotalPages
- total number of pagesFor example, to print the page number and total number of pages:
Page.printToPDF({
displayHeaderFooter: true,
footerTemplate: "<span class='pageNumber'></span> <span>out of</span> <span class='totalPages'></span>"
})
(At the time, this was not possible to achieve with Chrome DevTools.)
According to this forum, there is currently no way to do this in google chrome. All you can do is turn the header/footer on or off. This is indicated by the comment:
Currently there isn't a way to edit the header when printing a document. You can currently only turn the header and footer on or off which includes the date, name of the web page, the page URL and how many pages the document you're printing. You may want to check out the Chrome Web Store to see if there are any handy third party extensions that you can install on Chrome that may fit what you're looking for in terms of printing -- Source There may be third-party extensions to get the functionality you are looking for, or as you suggest, you can use JavaScript to append the elements you want to print.
For those of you who just want something that works out of the box, I would like to share my script I wrote today, based on the answer of apokryfos.
At first you need to install the dependencies
yarn global add chrome-remote-interface
Next you need to start a headless chromium with a debugging port enabled
chromium-browser --headless --disable-gpu --run-all-compositor-stages-before-draw --remote-debugging-port=9222
Now you have to save my script i.e. as print-via-chrome.js
:
#!/usr/bin/env node
const homedir = require('os').homedir();
const CDP = require(homedir+'/.config/yarn/global/node_modules/chrome-remote-interface/');
const fs = require('fs');
const port = process.argv[2];
const htmlFilePath = process.argv[3];
const pdfFilePath = process.argv[4];
(async function() {
const protocol = await CDP({port: port});
// Extract the DevTools protocol domains we need and enable them.
// See API docs: https://chromedevtools.github.io/devtools-protocol/
const {Page} = protocol;
await Page.enable();
Page.loadEventFired(function () {
console.log("Waiting 100ms just to be sure.")
setTimeout(function () {
//https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF
console.log("Printing...")
Page.printToPDF({
displayHeaderFooter: true,
headerTemplate: '<div></div>',
footerTemplate: '<div class="text center"><span class="pageNumber"></span></div>',
//footerTemplate: '<div class="text center"><span class="pageNumber"></span> of <span class="totalPages"></span></div>'
}).then((base64EncodedPdf) => {
fs.writeFileSync(pdfFilePath, Buffer.from(base64EncodedPdf.data, 'base64'), 'utf8');
console.log("Done")
protocol.close();
});
}, 100);
});
Page.navigate({url: 'file://'+htmlFilePath});
})();
After making it executable with chmod +x print-via-chrome.js
you should be able to convert html files to pdf files like so:
./print-via-chrome.js 9222 my.html my.pdf
Don't forget to quit the chromium after you finished your transformation.
I am pretty sure that this solution is far from perfect, but at least it works and as I saw a lot of questions about this feature and had to invest a few hours of my own time to get it working I wanted to share my solution. Some of the problems I had were related to the header- and footerTemplates as it seems that empty templates do not replace the existing ones (you need <div></div>
) and while differently documented the new templates do not appear in a visible region until wrapped with a <div class="text center">
or something similar.
As mentioned by Alec Jacobson in the comments, using margin:0 on the page along with margin:1.6cm on the body works only for one page.
What worked for me was to wrap my content in a table, using thead for the top margin and tfoot for the bottom margin. Thead and tfoot are repeated on all pages and your main page content goes in the tbody of the table.
Example:
`
<thead>
<tr>
<th style="height: 1cm">
Header
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Page Content
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td style="height: 1cm">
Footer
</td>
</tr>
</tfoot>
</table>`
Would have liked to have added to the comment thread but don't have enough reputation.
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>