20

我正在尝试使用 Wea​​syprint 库在 Django 上输出 PDF,但图像不会出现在生成的 PDF 上。我已经尝试了图像的相对和静态 URL,但即使是静态 URL 也不会显示图像。在 chrome 上打开 HTML 本身时,图像会显示。

这是views.py文件中我的pdf生成视图:

def pdf_generation(request, some_slug)
    stud = Student.objects.get(some_slug=some_slug)
    studid = stud.some_slug
    context = {'studid':studid}
    html_string = render_to_string('templates/pdf_gen.html', context)
    html = HTML(string=html_string)
    pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT +  '/css/detail_pdf_gen.css')]);
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="mypdf.pdf"'
    return response

这是图像的 HTML 部分:

<DIV id="p1dimg1">
<IMG src="{% static 'img/image.jpg' %}" alt="">
</DIV>

和CSS:

#page_1 #p1dimg1 {position:absolute;top:0px;left:0px;z-
index:-1;width:792px;height:1111px;}
#page_1 #p1dimg1 #p1img1 {width:792px;height:1111px;}

非常感谢

4

4 回答 4

38

修复者:

添加 base_url=request.build_absolute_uri()使得

html = HTML(string=html_string)

变成

html = HTML(string=html_string, base_url=request.build_absolute_uri())

这将允许 HTML 文件中的相对 URL。

对于图像,由于某种原因,似乎只有 PNG 图像有效。

要在 PDF 上显示 HTML 样式,请根据 Weasyprint 文档添加presentational_hints=True:

    pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT +  '/css/detail_pdf_gen.css')], presentational_hints=True);
于 2018-02-26T13:38:09.543 回答
7

将图像路径的静态设置为:

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

然后您必须将 Weasyprint 的 HTML 类中的 base_url 传递为:

HTML(string=html_string, base_url=request.build_absolute_uri())
于 2018-03-12T07:26:01.607 回答
4

添加HTML(string=html_string, base_url=request.build_absolute_uri())到我的配置图像后仍未加载。必须使用以下日志记录来识别真正的问题。

import logging
logger = logging.getLogger('weasyprint')
logger.addHandler(logging.FileHandler('/tmp/weasyprint.log'))

然后检查/tmp/weasyprint.log日志文件是否有错误。

对我来说真正的问题是:

urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate

修复是禁用 ssl 验证:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context
于 2020-10-21T12:54:52.937 回答
0

我不知道 Weasyprint,但我使用的是Pisa,它非常适合将图片转换为 PDF 输出。

例如 :

def PDFGeneration(request) :

    var1 = Table1.objects.last()
    var2 = Table2.objects.last()

    data = {"key1" : variable1, "key2" : variable2}

    html = get_template('My_template_raw.html').render(data)
    result = StringIO()

    with open(path, "w+b") as file :
      pdf = pisa.pisaDocument(StringIO(html), file, link_callback=link_callback)
      file.close()

      image_data = open(path, "rb").read()
      return HttpResponse(image_data, content_type="application/pdf")

    return render(request, 'HTML template', context)

def link_callback(uri, rel):
    if uri.find('chart.apis.google.com') != -1:
        return uri
    return os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))

我的 PDF 是从 .html 文件生成的,我的图片是这样的:

<html>
    <head>
    {% load staticfiles %}
    {% load static %}

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   
    <link rel="stylesheet" type="text/css" href="{% static 'css/MyFile.css' %}"/>

    <style>

            body {
                font-family: Courier New, Courier, monospace;
                text-align: justify;
                list-style-type: none;
            }
    </style>

    </head>

    <body>

        <img src="{{MEDIA_ROOT}}Logo/logo.jpeg" width="250" height="66"/>
        <br></br>
        ...
于 2018-02-26T13:02:25.987 回答