Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change paper size in headless Chrome --print-to-pdf

I am using headless Chrome to export html documents to pdf

google-chrome --headless --disable-gpu --print-to-pdf='output_path' 'url' 

How can I change paper size in generated pdf?

I have control on both Chrome parameters and html.

I always get US Letter.

There are no documented command-line options for this.

I've tried setting CSS: @page {size: A4;}. No effect in headless mode, but works when I hit Ctrl+P in normal mode (option to choose paper size for Save as pdf disappears, exported pdf has A4 page size).

I've tried this on Chrome versions 59, 60 and 61 on Ubuntu 16.04.

like image 995
Crazy Yoghurt Avatar asked Jul 07 '17 11:07

Crazy Yoghurt


People also ask

How do I change the page size in a PDF in Chrome?

Step 1: Click the three dots on the upper right corner of your Google Chrome browser to expand the More Options list. Step 2: Select Print. Step 3: Click on More Settings. Step 4: Select the correct paper size from the dropdown.

How do I customize print size in Chrome?

1. In Chrome's Print window, expand the More Settings section. 2. Select the desired paper size, such as '4 in x 6 in'.

How do I print to PDF in Chrome?

Open a webpage in Chrome, press Ctrl+P to open the Print dialog and change the destination printer to “Save as PDF”. Hit the “Print” button and the webpage will download as a PDF document.

What is headless mode in Chrome?

The Headless mode is a feature which allows the execution of a full version of the Chrome Browser. It provides the ability to control Chrome via external programs. The headless mode can run on servers without the need for dedicated display or graphics.


1 Answers

The page size could be set in inches/mm. I haven't tested with a size in pixels. Here is a set of CSS rules which did the trick for me:

@page {   margin: 0;   padding: 0;   size: 5in 6.5in; } 

My exact case is rendering svg-to-pdf, not html; For svg, you may also need to add width and height attributes to <svg> tag:

<svg width="5in" height="6.5in" ...> 

That's all! Output PDF won't have margins, and will preserve the desired size - 5"x6.5" in my case.

like image 111
Avael Kross Avatar answered Sep 28 '22 01:09

Avael Kross