Search code examples
pythonpdfkit

Convert html to pdf with material icons in python using pdfkit


I need to render a page to PDF file which includes Material icons but it doesn't seem to work.

templates/pdf.html

<html>
<head>
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

  <style>
    * {
      font-family: Roboto, Helvetica, sans-serif;
    }
</style>
</head>
<body>
  Just test 
  <i class="material-icons">remove_red_eye</i>
</body>
</html>

gen.py

import pdfkit
from django.template.loader import render_to_string

html = render_to_string('pdf.html')
pdfkit.from_string(html, 'out.pdf')
# I tried this version but it doesn't work either
# pdfkit.from_string(html, 'out.pdf', css=['https://fonts.googleapis.com/icon?family=Material+Icons'])

out.pdf only contains the text Just test. Are there any chance to fix it?

I've just also created the issue in pdfkit repo - issue


Solution

  • There are 2 issues to solve and I got it done in an acceptable manner.

    1. Css.

      • Only inline styles work. External styles don't work.

      • Wkhtmltopdf supports -webkit- prefix, so that some css properties need to add the prefix to work properly.

      • download external css files if required. Use <style>{% include 'style.css' %}</style> in django template to seperate out the css files.

    2. Icon fonts and custom fonts do not work.

      • download required svg icons instead of using icon fonts.

      a. use {% include 'icon.svg' %} to include the font icons

      b. only path, fill element in svg xml are supported

      c. you can change the color and height of svg in the svg xml content.

      d. download svgs at Material Icon

      e. you can use pngs instead but it is not easy to change the icon color and size.

      • use system font or install the font manually inside the serving instance.