使用Python Flask将html转换为pdf [英] Converting html to pdf using Python Flask
本文介绍了使用Python Flask将html转换为pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我在myclass.py中的代码
class Pdf():
$ b $ def render_pdf (self,name,html):
from xhtml2pdf import pisa
from StringIO import StringIO
pdf = StringIO()
pisa.CreatePDF(StringIO(html),pdf)
return pdf
@ app.route('/ invoice /< business_name> ; /< tin>',methods = ['GET'])
def view_invoice(business_name,tin):
#pdf = StringIO()
html = render_template (business_name,html)
return pdf
$($) c $ c>
但它会抛出这个错误
$ b $ pre $ code > AttributeError:StringIO实例没有__call__方法
解决方案
ng脚本对我很好。请注意我所做的更改:
$ ul
Pdf.render_pdf()
现在返回 pdf.getvalue()
,a str
。 view_invoice()
现在返回一个元组,以便可以设置Content-Type头。   ;
$ b $ $ b app = Flask(__ name__)
class Pdf():
$ b $ def render_pdf(self,name,html):
from xhtml2pdf import pisa
from StringIO import StringIO
pdf = StringIO()
pisa.CreatePDF(StringIO(html),pdf)
return pdf.getvalue()
@ app.route('/ invoice /< business_name> /< tin>',methods = ['GET'])
def view_invoice(business_name,tin):
#pdf = StringIO()
html = render_template(
'certificate.html',business_name = business_name,tin = tin )
file_class = Pdf()
pdf = file_class.render_pdf(business_name,html)
headers = {
'content-type':'application.pdf',
内容处置:附件; filename = certificate.pdf'}
return pdf,200,headers
$ b if __name__ =='__main__':
app.run(debug = True)
Here is my code in myclass.py
class Pdf():
def render_pdf(self,name,html):
from xhtml2pdf import pisa
from StringIO import StringIO
pdf = StringIO()
pisa.CreatePDF(StringIO(html), pdf)
return pdf
And I am calling it in api.py like this
@app.route('/invoice/<business_name>/<tin>', methods=['GET'])
def view_invoice(business_name,tin):
#pdf = StringIO()
html = render_template('certificate.html', business_name=business_name,tin=tin)
file_class = Pdf()
pdf = file_class.render_pdf(business_name,html)
return pdf
But it throws this error
AttributeError: StringIO instance has no __call__ method
解决方案
The following script worked well for me. Note the changes I made:
Pdf.render_pdf()
now returnspdf.getvalue()
, astr
.view_invoice()
now returns a tuple, so that the Content-Type header can be set.
#!/usr/bin/env python
from flask import Flask, render_template
app = Flask(__name__)
class Pdf():
def render_pdf(self, name, html):
from xhtml2pdf import pisa
from StringIO import StringIO
pdf = StringIO()
pisa.CreatePDF(StringIO(html), pdf)
return pdf.getvalue()
@app.route('/invoice/<business_name>/<tin>', methods=['GET'])
def view_invoice(business_name, tin):
#pdf = StringIO()
html = render_template(
'certificate.html', business_name=business_name, tin=tin)
file_class = Pdf()
pdf = file_class.render_pdf(business_name, html)
headers = {
'content-type': 'application.pdf',
'content-disposition': 'attachment; filename=certificate.pdf'}
return pdf, 200, headers
if __name__ == '__main__':
app.run(debug=True)
这篇关于使用Python Flask将html转换为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文