deflink_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ # use short variable names sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /static/media/ mRoot = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/
# convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png)
# make sure that file exists ifnot os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path
生成PDF代码如下,这里当把PDF当做附件,下载的时候浏览器会提示另存为下载框:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#生成pdf @app.route('/pdfdownload/', methods=['GET','POST']) defpdfdownload(): #其它业务代码 #填充pdf模板文件 html = render_template('pdfdownload.html') result = BytesIO() #生成pdf pdf = pisa.CreatePDF(BytesIO(html.encode('utf-8')),result,encoding='utf-8',link_callback=fetch_resources) resp = make_response(result.getvalue()) result.close() resp.headers["Content-Disposition"] = ("attachment; filename='{0}'".format('skxt-jkxj.pdf')) resp.headers['Content-Type'] = 'application/pdf' return resp