我的代码使用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()"statement.html.j2“
<img class="img-responsive" src="../img/image.png">镜像路径是否正确?如何引用模板中的图像?那将会是什么道路呢?或者问题与图像引用无关?
发布于 2021-11-18 10:57:36
这个问题已经在这里得到了回答:Image ignored in PDF rendering with jinja2 and weasyprint,
您需要在此处添加base_url='.':
HTML(string=html_out, base_url='.').write_pdf(outfile)https://stackoverflow.com/questions/52106531
复制相似问题