使用Weasyprint不显示图像的PDF输出(Django)

2024-05-16 08:06:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Weasyprint库在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;}

非常感谢


Tags: 文件图像urlstringpdfresponsehtml静态
3条回答

我不知道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>
        ...

修正者:

添加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);

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

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

然后,必须将Weasyprint的HTML类中的基url传递为:

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

相关问题 更多 >