Using wkhtmltopdf to generate a PDF from eZ Platform

I wanted to produce a polished PDF of restricted content managed by https://ezplatform.com/ with the least amount of effort possible and I wanted an approach that would allow me to run a single command on the command line.

My first approach was to try to use a browser's print to PDF feature, but I wasn't happy with the results. So I tried https://wkhtmltopdf.org/,

After tinkering with various roles/permissions and firewall configurations with eZ Platform and Symfony I chose to create a PDF user which was allowed to log in and view only the target content. I used curl to log in, extracted the eZ session id cookie and passed it to wkhtmltopdf for rendering.


#!/bin/bash
if [ "$#" -ne 1 ]; then
    echo "Usage: $0.sh url"
    exit;
fi;
USER=pdfuser
PASS=somepassword

URL=$1;
PDF=`echo $1 | sed "s/.*\/\([^\/]\+\)$/\1/"`
FOOTER_LEFT=${PDF^^}
LOGIN_URL=`echo $1 | sed "s/^\(https\?:\/\/[^\/]\+\/\).*$/\1login/"`
CSRF_TOKEN=`curl -s -X GET --cookie-jar cookie "$LOGIN_URL" | grep -o "name=\"_csrf_token\" value=\"\([^\"]\+\)\"" | sed "s/.*value=\"\([^\"]\+\)\"/\1/"`
LOGIN_DATA="_username=$USER&_password=$PASS&_csrf_token=$CSRF_TOKEN"
curl -L -s -b cookie --cookie-jar cookie -d "$LOGIN_DATA" "$LOGIN_URL"_check > /dev/null
COOKIE=`grep -o "\(eZSESS.*\)$" cookie | sed "s/\s\+/ /g"`
wkhtmltopdf --cookie $COOKIE --print-media-type --margin-left .5in --margin-right .5in --margin-top .5in --margin-bottom .5in "$URL" --footer-left "$FOOTER_LEFT" --footer-center 'Page [page] of [topage]' --footer-font-name 'Open Sans' --footer-font-size 8 --footer-right 'Updated [date]' "$PDF.pdf"

Thanks to: https://serverfault.com/a/306360/311430 for help with the cookies in the Apache log