Solve network errors with PDFKit and wkhtmltopdf
Mattia Orfano
Posted on June 14, 2022
In today's #10stips (where you learn how to solve coding issues within 10 seconds) we talk about the lovely PDFKit gem.
I've been using it since I was a child (ehm no.. since the gem was born around 12 years ago). It creates PDFs using plain old HTML+CSS.
PDFKit requires wkhtmltopdf
library which renders HTML using Webkit.
Now, Webkit is a rendering engine and depending on your system configuration you may stumble upon compatibility issues loading resources or unsolicited network errors that might drive you crazy, especially when you have HTML pages with lots of images.
PDFKit::ImproperWkhtmltopdfExitStatus UnknownNetworkError
Exit with code 1 due to network error: UnknownNetworkError
Exit with code 1 due to network error: ContentNotFoundError
Warning Failed to load
Basically, wkhtmltopdf fails to load CSS, JS or IMG files.
There are several factors playing a role...
- PDFkit 0.13 seems to work, while 0.12.5 does not.
- loading images from a web server with TLSv1, it works.
- on a modern server with TLS 1.2, it breaks but not for all resources.
- better to use absolute paths instead of relative ones
- who knows, who cares!?!?!?!
So, I give you a quick and final solution.
Ready?
Turn off the computer and go on a hike. Seriously, it helps your mental and physical health.
But if you're still interested to solve the problem, this is what I suggest...
- If possible, update your wkhtmltopdf to the latest version
- Check wether external resources in your HTML comes from a TLSv1 or TLSv2 server (newer versions of wkhtmltopdf work best with TLSv2).
- Try to switch URLs from HTTPS to HTTP (and viceversa)
- Set
config.default_options[:ignore_load_errors] = true
in your PDFKit.configure block
Obviously, using HTTP versus HTTPS presents a security concern. Unfortunately, we have very few options and I'm a guy who prioritize sanity over bugfixing.
And remember, sometimes it's OK to pretend bugs are features.
Leave a thumbs up and comment if you wish.
Posted on June 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.