Site icon Shaharia's Blog

Google Web Fonts for wkhtmltopdf to convert HTML to PDF

Google Web Fonts for wkhtmltopdf to convert HTML to PDF

Google Web Fonts for wkhtmltopdf to convert HTML to PDF

I receive very frequent request from clients to use custom fonts they chose for their expected PDF. And most of them choose fonts from Google Web Fonts because of their extended library. I also love it for all of our front-end projects. So I ended up facing with the issue to use Google Web Fonts for wkhtmltopdf. After searching a lot I have found the solutions by myself and I realized that I should write about it all the pieces altogether so like you other can save their valuable time.

Use TrueType instead woff

To convert HTML to PDF by wkhtmltopdf try to avoid woff font face. Use truetype format of the Google Web Fonts with base64 encode.

Recently I tried to use a google web font from Google Web Fonts. But in browser it shows correctly but it doesn’t show after converting HTML to PDF.

Base64 Encoding

Then after searching and spending lots of time on internet, I found tools to encode fonts to base64 encoded format and also got CSS for @font-face.

The base64 encoded string and CSS @font-face code snippet given below :

Define font-face

@font-face {
    font-family: 'Port Lligat Slab';
    font-style: normal;
    font-weight: 400;
    src: url(data:font/opentype;charset=utf-8;base64,d09GRgABAAAAAD00AA4A---[large string ommited]----3MAuAH/hbAEjQA=) format("woff"),
    url(data:font/truetype;charset=utf-8;base64,AAEAAAARAQAABAAQRFNJRwAAAAEAAJUIAAA---[large string ommited]-----wAAAAAAAAAAAAEAAAAA) format("truetype");
}

I used http://www.opinionatedgeek.com/dotnet/tools/base64encode/ to encode the font file. But remember you need encoded string for both woff and truetype (ttf). So now your document will be easily converted to PDF by wkhtmltopdf tools.

Please let me know if this solutions works or if you face any trouble using Google Web Fonts for wkhtmltopdf to convert HTML to PDF please write that too in comment box below. So others can understand easily.