gpt4 book ai didi

python - 在 pdf weasyprint 中附加 img 文件

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:40 28 4
gpt4 key购买 nike

我需要有关在 pdf 中附加 img 文件的帮助。我们使用 Wea​​syPrint 库从 html 生成 pdf。

在html中像这样连接img文件

<img src="1.png" alt="">
<img src="2.png" alt="">
<img src="3.png" alt="">

但它不起作用。我没有看到图像。

最佳答案

图片文件路径使用static

  {% load static %}
<img src="{% static 'images/static.jpg' %}" alt="">

并在 views.py 的 HTML 类中传递 base_url

pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri())

html文件

<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<img src="{% static 'images/static.jpg' %}" alt="">
</div>
</body>
</html>

View .py

from django.template.loader import get_template
from weasyprint import HTML, CSS
from django.conf import settings
from django.http import HttpResponse


def generate_pdf(request):
html_template = get_template('latest/html_pdf.html')
user = request.user
rendered_html = html_template.render().encode(encoding="UTF-8")
pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri()).write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/generate_html.css')])



http_response = HttpResponse(pdf_file, content_type='application/pdf')
http_response['Content-Disposition'] = 'filename="generate_html.pdf"'

return http_response

关于python - 在 pdf weasyprint 中附加 img 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43539702/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com