Python3 Django - > HTML到PDF [英] Python3 Django -> HTML to 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')
$要将Django视图呈现为HTML,您可以使用快捷方式 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屋!