【问题标题】:Render image in template.html with Jinja2 and weasyprint in a PDF使用 Jinja2 和 weasyprint 在 PDF 中渲染 template.html 中的图像
【发布时间】:2021-09-18 02:38:13
【问题描述】:

我有一个 python 文件,可以像这样使用 jinja2 生成 HTML 页面(和 PDF)。

import pandas as pd
import requests
from jinja2 import Environment, FileSystemLoader
from weasyprint import HTML

# Stuff to get dataframe...

# Generate PDF and csv
env = Environment(loader=FileSystemLoader('.'))
template = env.get_template("template.html")

template_vars = {"title" : "Something...",
                "vulnerabilities_table": df.to_html(index=False)}

html_out = template.render(template_vars)
HTML(string=html_out).write_pdf("report_styled.pdf", stylesheets=["style.css"])

它使用以下template.html

<!DOCTYPE html>
{% block layout_style %}
<style> @page { size: letter landscape; margin: 2cm; } </style>

{% endblock %}
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>{{ title }}</title>
</head>
<body>
    <img src="static/images/Logo.png" style="height: 100; width: 300; float:inline-start">
    <h2>{{ title }}</h2>
     {{ vulnerabilities_table }}
</body>
</html>

问题是图像根本没有渲染(但其余部分)。我猜是因为我没有使用 Flask

<img src="static/images/Logo.png" style="height: 100; width: 300; float:inline-start">

我的图片位于文件夹 static/images/Logo.png 中。我做错了什么?

【问题讨论】:

    标签: python jinja2 weasyprint


    【解决方案1】:

    问题不在于 Flask。这是关于 weasyprint 将 html 页面(在您的情况下实际上是 html 字符串)转换为 PDF。对于weasyprint HTML 类来获取img 源(static/images/Logo.png),您需要将完整的本地文件路径设置为file:///path/to/folder/static/images/Logo/png

    你可以做的是,在template.html:

    <img src="{{ image_path }}" style="height: 100; width: 300; float:inline-start">
    

    在python代码中:

    import os
    this_folder = os.path.dirname(os.path.abspath(__file__))
    template_vars = {"title" : "Something...",
                    "vulnerabilities_table": "hello world",
                     "image_path": 'file://' + os.path.join(this_folder, 'static', 'images', 'Logo.png' )}
    html_out = template.render(template_vars)
    HTML(string=html_out).write_pdf("report_styled.pdf", stylesheets=["style.css"])
    

    【讨论】:

    • 您指出了问题所在,解决方案完美运行。我完全误解了这个问题。相应地更改标题以匹配。谢谢
    猜你喜欢
    • 2019-12-04
    • 2019-02-05
    • 2014-02-03
    • 2019-11-08
    • 2021-05-26
    • 2018-06-05
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    相关资源
    最近更新 更多