简体   繁体   中英

jinja2 and weasyprint path to image

My code convert the jinja2 template into PDF using weasyprint. Everything work fine except I can't get the image to appear in the PDF.

My files structure:

dist
src
    img
        image.png
    templates
        statement.html.j2
build.py

"build.py"

import jinja2
import json
import os
import weasyprint
from weasyprint.fonts import FontConfiguration


def main():
    if not os.path.exists('dist'):
        os.makedirs('dist')
    jinja_env = jinja2.Environment(
            loader = jinja2.FileSystemLoader('src/templates')
        )
    css_dir = 'src/css'
    html_tpl = jinja_env.get_template('statement.html.j2')
    with open('sample/json/statement.json', 'r') as f:
        statement = json.load(f)
    statement = statement['statement']
    font_config = FontConfiguration()
    html = html_tpl.render(statement=statement)
    css_files = [weasyprint.CSS(os.path.join(css_dir, filename))
        for filename in os.listdir(css_dir)]
    rendered_html = weasyprint.HTML(
        string=html
    )
    rendered_html.write_pdf(
        'dist/statement.pdf',
        stylesheets=css_files,
        font_config=font_config
    )

if __name__ == '__main__':
    main()

"statement.html.j2"

<img class="img-responsive" src="../img/image.png">

Is the image path correct? How I can reference the image in the template? What will be the path then? Or the issue is not related to the image reference?

This question has been answered here : Image ignored in PDF rendering with jinja2 and weasyprint ,

you need to add base_url='.' here :

HTML(string=html_out, base_url='.').write_pdf(outfile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM