在 pdf weasyprint 中附加 img 文件

Use*_*r34 8 python django pdf-generation weasyprint

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

在html中像这样连接img文件

<img src="1.png" alt="">
<img src="2.png" alt="">
<img src="3.png" alt="">
Run Code Online (Sandbox Code Playgroud)

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

Tha*_*eem 10

使用静态作为图像文件的路径

  {% load static %}
    <img src="{% static 'images/static.jpg' %}" alt="">
Run Code Online (Sandbox Code Playgroud)

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

pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri())
Run Code Online (Sandbox Code Playgroud)

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

视图.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
Run Code Online (Sandbox Code Playgroud)

  • 如果你只是想确保图像包含在纯Python中并且你不使用django或模板做任何事情,那么你需要的只是“base_url”,如果你在本地工作,它可以是“.” (3认同)