使用Weasyprint的PDF输出不显示图像(Django) [英] PDF output using Weasyprint not showing images (Django)

查看:418
本文介绍了使用Weasyprint的PDF输出不显示图像(Django)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to output PDF on Django using the Weasyprint library, but the images don't appear on the generated PDF. I have tried both relative and static URLs for the images, but even the static URL doesn't show the image. When opening the HTML itself on chrome, the images do show.

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

Here is my pdf generation view in the views.py file:

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的一部分:

Here is the part of the HTML of the image:

<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;}

非常感谢您

推荐答案

固定于:

添加base_url=request.build_absolute_uri()以便

html = HTML(string=html_string)

成为

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

这将允许在HTML文件中使用相对URL.

That will allow for relative URLs in the HTML file.

对于图像,由于某些原因,似乎只有PNG图像可以工作.

For the images, only PNG images seems to work for some reason.

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

For the HTML styles to show on the PDF, add presentational_hints=True as per the Weasyprint docs:

    pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT +  '/css/detail_pdf_gen.css')], presentational_hints=True);

这篇关于使用Weasyprint的PDF输出不显示图像(Django)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆