jinja2 and weasyprint path to image



我的代码使用 weasyprint 将 jinja2 模板转换为 PDF。 一切正常,除了我无法让图像出现在 PDF 中。

我的文件结构:

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()

"声明.html.j2">

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

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

这个问题已经在这里得到了回答: 使用 jinja2 和 weasyprint 的 PDF 渲染中忽略图像,

您需要在此处添加base_url='.'

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

最新更新