Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python jinja2和weasyprint到图像的路径_Python_Jinja2_Weasyprint - Fatal编程技术网

Python jinja2和weasyprint到图像的路径

Python jinja2和weasyprint到图像的路径,python,jinja2,weasyprint,Python,Jinja2,Weasyprint,我的代码使用weasyprint将jinja2模板转换为PDF。 一切都很好,除了我无法将图像显示在PDF中 我的文件结构: dist src img image.png templates statement.html.j2 build.py “build.py” “statement.html.j2” 图像路径正确吗? 如何在模板中引用图像? 那么,道路将是什么? 或者问题与图像引用无关?根据您所说的目录结构,您的相对路径似乎是正确的,但

我的代码使用weasyprint将jinja2模板转换为PDF。 一切都很好,除了我无法将图像显示在PDF中

我的文件结构:

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

“statement.html.j2”


图像路径正确吗? 如何在模板中引用图像? 那么,道路将是什么?
或者问题与图像引用无关?

根据您所说的目录结构,您的相对路径似乎是正确的,但只是为了排除故障,如果你用图像的完整路径替换
。/img/image.png
,你还会有问题吗?@HFBrowning如果我给出绝对路径,那就没问题了。这就是你的问题所在。只要确定你的相对路径,你就应该被设置好。
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()
<img class="img-responsive" src="../img/image.png">