使用 Jinja2 和 weasyprint 在 PDF 中渲染 template.html 中的图像

Soa*_*lex 5 python jinja2 weasyprint

我有一个 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"])
Run Code Online (Sandbox Code Playgroud)

它使用以下内容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>
Run Code Online (Sandbox Code Playgroud)

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

<img src="static/images/Logo.png" style="height: 100; width: 300; float:inline-start">
Run Code Online (Sandbox Code Playgroud)

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

nng*_*eek 9

问题不在于 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">
Run Code Online (Sandbox Code Playgroud)

在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"])
Run Code Online (Sandbox Code Playgroud)