additional options in Chrome headless print-to-pdf

user2580925 picture user2580925 · Sep 6, 2017 · Viewed 39k times · Source

I need help one more time. I am trying to print a page to pdf using headless feature of the chrome. However, header and footer is present in the pdf. I found that this option as been implemented in Devtools.

https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF

However, i can't find how can i use these options in CLI. Also is it possible to invoke the Devtools from selenium?

Additionally how can i invoke Page.PrintToPDF in Dev tools. I tried to run the command in Console. It is showing Page is undefined.

Answer

nuccio picture nuccio · Dec 5, 2017

Add this CSS to the page your creating into a PDF to remove Chrome Headless's implemented Header and Footer.

CSS:

@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}

You should format your command like below to create the PDF:

"C:\PATH\TO\CHROME\EXECUTABLE\FILE", "--headless","--disable-gpu","--print-to-pdf=" + directory path to where you want the file to go followed by the desired file name/fileName.pdf,"--no-margins", "the path to the file you want turned into a pdf"

Example 1:

C:\chrome-win/chrome --headless --disable-gpu --print-to-pdf=C:\user\fileName.pdf --no-margins C:\Projects\index.html

Example 2:

You can also test this functionality by navigating in your command line to the folder containing Chrome executable file, and running this command:

chrome --headless --disable-gpu --print-to-pdf https://www.chromestatus.com/