Blog
[Solved] Headless Chrome options ignoring landscape mode when printing to pdf
We ran into a tough debugging issue this morning when a customer wrote in saying that our .NET client library was not generating his PDFs in ‘landscape’ mode while using Headless Chrome. The customer provided all of their C# code and I went to work trying to figure out what’s going on.
He was using the chrome/url endpoint, so he has a web page he wants to convert to PDF.
Step 1: Run his code ‘as-is’. The C# code looked completely correct. It was a near exact copy of our sample code from the github README. So this was worrisome.
Step 2: I tested the exact same options by going straight to our documentation and using the swagger functionality to test the API directly. This too yielded a PDF in portrait mode when it should have been rendered in landscape mode. This was even more problematic because it would indicate a problem with the API for all people using it, rather than just those using the .NET client library.
Step 3: Try with wkhtmltopdf instead of Headless Chrome. Well…It renders landscape in wkhtmltopdf but not Headless Chrome. Why?!?!
Step 4: Go back to Headless Chrome and try with a web page that I’m familiar with. So far, with steps 1 and 2, I neglected to test even the most basic page. My go-to test is github.com. I tested the same exact options but this time with github.com as the url instead of the customer’s own page. Boom, landscape rendered just fine!
This was important because it told me that it has nothing to do with our API, no our client libraries. There must be something on the customer’s website forcing portrait mode.
Step 5: Using Chrome’s inspect element, I started opening up all the linked CSS files that were there. In bootstrap.min.css, I found one very important style:
@page{size:a3}
This css will force the page to appear as A3 size when printing to PDF using Headless Chrome, regardless of the options you have set in API2PDF. To fix the issue, remove this css. It should be noted that wkhtmltopdf does not know how to render that styling which is why it generated in landscape mode and Headless Chrome did not.
Mystery solved!