Goal
wkhtmltopdf is a tool to generate PDF files from HTML. It can also be used from within drupal. This article will explain how to install it on platform.sh
Installing
You can install the wkhtmltopdf-binary using the ruby gem. You do not need to run ruby to be able to use this.
Add this to your .platform.app.yaml
dependencies to install:
dependencies:
ruby:
"wkhtmltopdf-binary": "> 0.12.5.1"
Note that you can specify the binary version. Check the ruby gem maintainer for a full list of all versions.
Important: Make sure you also add wkhtmltopdf -V
to your build hook. This is needed because of the way the ruby gem works. The first time it runs, it unpacks the correct binary into your /app folder. And since we have a read-only files system by design, this can only be done in the build hook.
hooks:
build: |
wkhtmltopdf -V
Usage
When you’re using the drupal wkhtmltopdf it should already be working.
You can also use a wrapper e.g.
https://github.com/mikehaertl/phpwkhtmltopdf
The default examples should work
use mikehaertl\wkhtmlto\Pdf;
// You can pass a filename, a HTML string, an URL or an options array to the constructor
$pdf = new Pdf('/path/to/page.html');
if (!$pdf->saveAs('/path/to/page.pdf')) {
$error = $pdf->getError();
// ... handle error here
}
If you have any other way of using it, make sure you are calling the alias wkhtmltopdf
. Don’t use /app/.global/gems/wkhtmltopdf-binary-0.12.5/bin/wkhtmltopdf
because that will cause problems upon upgrading the version.
e.g.
<?php
system('wkhtmltopdf https://platform.sh platformsh.pdf');
Possible issues
I’m getting SSL errors when generating a page.
wkhtmltopdf is a headless webbrowser that opens your html and all assests (img, css, js). Make sure all assets are referenced relatively and do not have an absolute path. If you still continue to see errors, try upgrading to the next version of wkhtmltopdf.
Error: Failed loading page xxxxx (sometimes it will work just to ignore this error with --load-error-handling ignore)
See above.
No stderr output available
wkhtmltopdf ["/app/.global/bin/wkhtmltopdf" -q --page-size A4 --orientation portrait --dpi 96 - -] (returned 1): No stderr output available.
Have you put wkhtmltopdf -V
in the build hook? Are you seeing errors in the build hook as well?
My wkhtmltopdf version suddenly upgraded to a newer version and no longer works!
You probably haven’t defined a version for wkhtmltopdf-binary
Change this:
dependencies:
ruby:
"wkhtmltopdf-binary": "> 0.0"
to this:
dependencies:
ruby:
"wkhtmltopdf-binary": "> 0.12.5"
or any other version you specifically require.