[英]Render image in template.html with Jinja2 and weasyprint in a PDF
我有一個 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 中。 我做錯了什么 ?
問題不在於 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"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.