[Resolved] PDF is rendering blank or only partially with Headless Chrome

April 8th, 2020 / by api2pdf /

Intro

In this post we will outline why in some cases PDFs are rendering blank or maybe only some elements, or part of elements are appearing but not everything on the page. We are going to explain why this occurs when rendering PDFs with Headless Chrome, but it would impact any browser based engine. Common causes:

  • You are using a javascript library / framework, or a lot of custom javascript to render the elements on the page.
  • Your page is rendering large images or SVG elements that take some extra time to actually render on the screen.

Why is this happening?

When PDF guidelines were invented, there was no concept of javascript or dynamic content on the web. A PDF, for all intents and purposes, is a printed piece of paper – static content. And so the rendering engine, Headless Chrome in this case, is loading your HTML or URL and the exact moment it loads your content, it will take a snapshot and render it to PDF.

However, just because the content got pulled in doesn’t mean it had time to run the custom javascript or render the images on the screen. That takes extra time. But Headless Chrome is not waiting, it is taking a snapshot of the PDF before the other elements have enough time to appear.

How do I fix blank or partially blank PDFs?

You have a couple options.

  1. Go old school – rebuild your HTML so that you are spitting out straight HTML and CSS and optimized images server-side so that there is no dynamic content generation with javascript.
  2. You worked really hard on it and don’t want to change any code? Make sure you are using our v2 API which supports a delay attribute that you can specify how long for the engine to wait before taking a snapshot of your page to PDF. See example below.

V2 API Delay Render with Headless Chrome

If you are already an API2PDF user, you have an API key. If you are looking to generate PDFs, you can quickly grab an API key from here.

See our v2 Headless Chrome documentation here: https://app.swaggerhub.com/apis-docs/api2pdf/api2pdf/2.0.0-beta

If you are migrating from v1 api, take note that the v2 base endpoint is https://v2.api2pdf.com and chrome’s URL to PDF endpoint is https://v2.api2pdf.com/chrome/pdf/url.

Observe the advanced option in the payload called delay. This value is set to milliseconds. For example, if you wanted to wait for 1 second, you would set this value to 1000. Set this value as high as necessary to ensure all elements render into the PDF.

Here is an example usage in Python.

Tags: , , ,

Comments are closed.