Python3 Django - > HTML到PDF [英] Python3 Django -> HTML to PDF

查看:101
本文介绍了Python3 Django - > HTML到PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python2中,有很多不同的方式从django网页生成pdf。最干净的,可能是比萨和报告。
这些不适用于python3。



到目前为止,我已经取得成功的唯一方法是渲染模板,将其写入文件,然后通过subprocess.popen使用wkhtmltopdf。这样做很好,但它不加载任何我的静态文件,如css和图像。



有没有正确的解决方案?可以wkhtmltopdf从命令行读取我的静态文件,在某种程度上,还是有像pisa / reportlab这样的支持python3的库?



我还没有找到这样一个图书馆

解决方案

你可以使用 Weasyprint 。你可以直接轻松渲染。



您可以这样做:

  html = HTML string = htmlstring)
main_doc = html.render()
pdf = main_doc.write_pdf()
return HttpResponse(pdf,content_type ='application / pdf')
render_to_string(self.template_name,context, context_instance = RequestContext(self.request))



请注意,当与同步Web服务器/ WSGI服务器一起使用时,所有请求将被阻止,直到呈现PDF。所以考虑使用ASYNC Worker。


There are a lot of different ways of generating pdfs from a django webpage in python2. The most clean, probably, is pisa and reportlab. These do not work for python3 though.

So far, the only method I've had success with is to render the template, write it to a file, and then use wkhtmltopdf via subprocess.popen. This works alright, but it doesn't load any of my static files, such as css and images.

Are there any proper solutions? can wkhtmltopdf read my staticfiles from the command line, in some way, or is there a library like pisa/reportlab, which supports python3?

I haven't been able to finde such a library

解决方案

You could use Weasyprint. You could easily render directly.

You could do something like that:

    html = HTML(string=htmlstring)
    main_doc = html.render()
    pdf = main_doc.write_pdf()
    return HttpResponse(pdf, content_type='application/pdf')

To render your Django view to HTML, you could simply use the shortcut render_to_string(self.template_name, context, context_instance=RequestContext(self.request))

Be aware, when using This with a Synchronous Webserver/WSGI Server ALL requests will be blocked until the PDF is rendered. So consider using an ASYNC Worker.

这篇关于Python3 Django - > HTML到PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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