Getting the Base URI for Weasyprint in Python Getting the Base URI for Weasyprint in Python flask flask

Getting the Base URI for Weasyprint in Python


I had the same error I had this tag, on OSX, in a template that I rendered with pystache:

<img src="/Users/my_username/my_project/my_image.png" />

So I tried this instead and it worked:

<img src="file:///Users/my_username/my_project/my_image.png" />

Just add file:// before the /Users/... path. (Note that it's 3 slashes).


I figured out that base_url had to be given as an arg to the weasyprint.CSS function and not to the weasyprint.HTML one:

from weasyprint import HTML, CSShtml_content = '''<h1>The title</h1><p>Content goes here'''base_url = os.path.dirname(os.path.realpath(__file__))css = CSS(string='body{background-image: url("example_image.png")}', base_url=base_url)HTML(string=html_content).write_pdf("hello.pdf", stylesheets=[css])

As a bonus, the same with loading local fonts located in a fonts folder placed aside this script:

# for debuggingimport logginglogger = logging.getLogger('weasyprint')logger.addHandler(logging.StreamHandler())import osfrom weasyprint import HTML, CSSfrom weasyprint.fonts import FontConfigurationhtml_content = '''<h1>The title</h1><p>Content goes here</p>'''font_config = FontConfiguration()THIS_FILE_DIR = os.path.dirname(os.path.abspath(__file__)) + os.sepbase_url = 'file://' + THIS_FILE_DIR# fonts downloaded from# https://fonts.google.com/specimen/Poppins?preview.text_type=custom&sidebar.open=true&selection.family=Poppins:wght@400;500;600;700css = CSS(string='''        @font-face {          font-family: 'Poppins';          src: url('./fonts/Poppins-Regular.ttf') format('truetype');          font-weight: 400;          font-style: normal;        }                @font-face {          font-family: 'Poppins';          src: url('./fonts/Poppins-Medium.ttf') format('truetype');          font-weight: 500;          font-style: normal;        }                @font-face {          font-family: 'Poppins';          src: url('./fonts/Poppins-SemiBold.ttf') format('truetype');          font-weight: 600;          font-style: normal;        }                @font-face {          font-family: 'Poppins';          src: url('../base/fonts/Poppins-Bold.ttf') format('truetype');          font-weight: 700;          font-style: normal;        }        ''', font_config=font_config, base_url=base_url)HTML(string=html_content).write_pdf("hello.pdf", stylesheets=[css])