在Django网站中将HTML渲染为PDF

对于我的django网站,我正在寻找一种将动态html页面转换为pdf的简单解决方案。

页面包含HTML和来自Google可视化API的图表(该图表基于javascript,但必须包含这些图表)。


开心每一天1111
浏览 848回答 3
3回答

BIG阳

我只是为CBV打了个招。未在生产中使用,但会为我生成PDF。可能需要为错误报告方面的事情工作,但到目前为止已经可以解决问题。import StringIOfrom cgi import escapefrom xhtml2pdf import pisafrom django.http import HttpResponsefrom django.template.response import TemplateResponsefrom django.views.generic import TemplateViewclass PDFTemplateResponse(TemplateResponse):&nbsp; &nbsp; def generate_pdf(self, retval):&nbsp; &nbsp; &nbsp; &nbsp; html = self.content&nbsp; &nbsp; &nbsp; &nbsp; result = StringIO.StringIO()&nbsp; &nbsp; &nbsp; &nbsp; rendering = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)&nbsp; &nbsp; &nbsp; &nbsp; if rendering.err:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.content = result.getvalue()&nbsp; &nbsp; def __init__(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; super(PDFTemplateResponse, self).__init__(*args, mimetype='application/pdf', **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; self.add_post_render_callback(self.generate_pdf)class PDFTemplateView(TemplateView):&nbsp; &nbsp; response_class = PDFTemplateResponse像这样使用:class MyPdfView(PDFTemplateView):&nbsp; &nbsp; template_name = 'things/pdf.html'
打开App,查看更多内容
随时随地看视频慕课网APP