【问题标题】:Image ignored in PDF rendering with jinja2 and weasyprint使用 jinja2 和 weasyprint 在 PDF 渲染中忽略图像
【发布时间】:2019-12-04 07:27:35
【问题描述】:

我在 python 中运行一个分析脚本,它给了我一些变量和一个我保存为png 文件的图像。然后我使用jinja2 将它们填充到html 模板中,然后使用weasyprint 将html 呈现为我保存的PDF 文件。

这里有很多关于这个问题的问题,但没有一个建议的解决方案能解决我的问题。我需要将图像的 absolute 路径提供给它,因为输出数据与生成它的代码保存在我本地磁盘的完全不同的部分。许多提供的解决方案建议使用request.base_url() 之类的东西,但这似乎来自flask(我猜?)或者实际上是在构建应用程序而不是简单地构建PDF文件。

从变量生成 PDF 文件的函数如下所示:

def create_pdf_report(varlist, outfile):

    # Create Jinja environment and get template
    from jinja2 import Environment, FileSystemLoader
    env = Environment(loader=FileSystemLoader('<absolute-path-to-dir-with-template>'))
    template = env.get_template('report_template.html')

    # Render HTML with input variables
    html_out = template.render(varlist)

    # Generate PDF
    from weasyprint import HTML
    HTML(string=html_out).write_pdf(outfile)

模板是这样的:

<img src="{{ systematics_figure }}" alt="systematics" width="900" height="650">

而我传入的varlist 字典看起来像这样:

fig3_fname = '<absolute-path-to-image>'
varlist = {'systematics_figure': fig3_fname}

虽然我给它的普通变量渲染得很好,但图像没有显示;我得到了它的alt 文本。该过程完成得很好,但我无法显示png 图像。当我直接将绝对图像路径粘贴到html文件中并在浏览器中打开它时,它看起来很好。

我可以做些什么来完成这项工作?

我使用的是 macOS Sierra 10.12.6 并使用 python 3.7.3。

【问题讨论】:

    标签: python image pdf jinja2 weasyprint


    【解决方案1】:

    原来解决方案是在weasyprint.HTML() 中添加base_url='.'

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

    并使用png 文件而不是pdf 数字。

    【讨论】:

    • 我的朋友!你是救世主!太感谢了!我希望我能投票两次:-)
    • 确实!花了几天的时间。如果没有这个答案,我不可能想到这一点。谢谢!
    猜你喜欢
    • 2021-09-18
    • 2019-02-05
    • 2014-02-03
    • 2019-11-08
    • 1970-01-01
    • 2018-06-05
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多