Run wkhtmltopdf With Chinese Font Support on Travis CI


Run wkhtmltopdf on Travis CI, which convert HTML files with chinese characters to PDF.

We need to overcome the following two problems:

  1. error message: wkhtmltopdf: cannot connect to X server

    The solution comes from this answer on Stack Overflow. Add the following lines in your .travis.yml

    sudo: required
    dist: trusty
    before_install:
    - sudo apt-get -qq update
    - sudo apt-get install -y xfonts-75dpi
    - wget http://download.gna.org/wkhtmltopdf/0.12/0.12.2/wkhtmltox-0.12.2_linux-trusty-amd64.deb
    - sudo dpkg -i wkhtmltox-0.12.2_linux-trusty-amd64.deb
    
  2. wkhtmltopdf Chinese character support

    The solution comes from this blog post. Add the following lines in your .travis.yml

    before_install:
    - sudo apt-get install -y language-pack-zh-hant fonts-wqy-microhei ttf-wqy-microhei fonts-wqy-zenhei ttf-wqy-zenhei
    install:
    - fc-cache -f -v
    

Combine the above two solution together, your final .travis.yml will looks like:

sudo: required
dist: trusty
before_install:
- sudo apt-get -qq update
- sudo apt-get install -y language-pack-zh-hant fonts-wqy-microhei ttf-wqy-microhei fonts-wqy-zenhei ttf-wqy-zenhei
- sudo apt-get install -y xfonts-75dpi
- wget http://download.gna.org/wkhtmltopdf/0.12/0.12.2/wkhtmltox-0.12.2_linux-trusty-amd64.deb
- sudo dpkg -i wkhtmltox-0.12.2_linux-trusty-amd64.deb
install:
- fc-cache -f -v

Example Bash script to run wkhtmltopdf:

#!/bin/bash

# $1 is the directory in which files to be processed
# $2 is the css file
for path in $(find $1 -name "*.html")
do
  echo -e "\033[92mProcessing ${path}\033[0m"
  wkhtmltopdf ${path} --disable-javascript --user-style-sheet $2 "${path%.html}.pdf"
done

Tested on: Travis CI - The Trusty beta Build Environment, http://download.gna.org/wkhtmltopdf/0.12/0.12.2/wkhtmltox-0.12.2_linux-trusty-amd64.deb


References:

[1]

wkhtmltopdf: cannot connect to X server - Google search

xserver - wkhtmltopdf: cannot connect to X server - Stack Overflow

[2]

wkhtmltopdf chinese font - Google search

pdf - wkhtmltopdf and chinese characters - Stack Overflow

wkHTMLToPDF chinese character support on Linux based systems | Clement Nedelcu's Development Journal

[3]

Installing Dependencies - Travis CI

The Build Environment - Travis CI

The Trusty beta Build Environment - Travis CI

[4][Bash] HTML to PDF via wkhtmltopdf