Search code examples
pythonwkhtmltopdf

Conversion of HTML to PDF using wkhtmltopdf failed


For setup I ran:

sudo apt-get install wkhtmltopdf
pip install pdfkit==0.6.1

Now, I am trying to run the following code on a VM in the cloud:

import pdfkit
pdfkit.from_file("foo.html", "foo.pdf", options={"javascript-delay": 10000})

The javascript-delay argument is necessary because otherwise some parts are not rendered correctly. This command works fine on my local machine, but in the cloud I get the following error message:

wkhtmltopdf exited with non-zero code 1. error:
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'
qt.qpa.screen: QXcbConnection: Could not connect to display
Could not connect to any X display.

Any idea how to fix this error OR ideas about an alternative way of converting an .html to a .pdf?


Solution

  • After a lot of trial and error, this is what I added to my Dockerfile to make it work:

    RUN apt-get update && apt-get install -yq gdebi
    
    RUN TEMP_DEB="$(mktemp).deb" \
      && wget -O "$TEMP_DEB" 'https://github.com/wkhtmltopdf/packaging/releases/download/0.12.1.4-2/wkhtmltox_0.12.1.4-2.bionic_amd64.deb' \
      && sudo apt install -yqf "$TEMP_DEB" \
      && rm -f "$TEMP_DEB"
    
    

    So basically installing gdebi and then installing a different version of wkhtmltox.