【问题标题】:PDF output using Weasyprint not showing images (Django)使用 Wea​​syprint 的 PDF 输出不显示图像(Django)
【发布时间】:2018-08-05 22:06:54
【问题描述】:

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

非常感谢

【问题讨论】:

    标签: python html django pdf weasyprint


    【解决方案1】:

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

    【讨论】:

    • 我一直在干预代码,直到我对自己产生了一些严重的怀疑并尝试了其他图片,似乎只显示了 png 图像。也许这是错误的css,或者我可能只需要将所有图像转换为png。不过感谢您的回答!
    • 好的。这很奇怪,但是一年前,我正在寻找一种获取带有图片的 PDF 的好方法,而 Pisahtml2pdf 似乎是做到这一点的最佳工具;)我没有任何问题,而且效果很好。如果我的回答对您有所帮助,请不要犹豫投票。
    【解决方案2】:

    修正者:

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

    【讨论】:

    • 问题是,为什么 JPG 不起作用。 PNG 工作正常。
    • 这是帮助我的部分“对于图像,由于某种原因,似乎只有 PNG 图像有效。”
    • 如果是 JPG 图片,安装 gdk-pixbuf 包解决了我的问题。对于 Ubuntu sudo apt-get install libgdk-pixbuf2.0-0
    【解决方案3】:

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

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

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

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

    【讨论】:

    • 尝试了您的解决方案,但出现错误 unorderable types: str() > float()
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 2021-10-20
      • 2020-01-30
      • 2021-09-23
      • 2019-06-06
      • 2016-09-26
      • 2018-01-24
      • 2019-07-21
      • 1970-01-01
      相关资源
      最近更新 更多