<p>改进@V Stoykov answer,因为它帮助我使用<strong>烧瓶</strong>,在<strong>烧瓶</strong>中使用自定义标题的渲染函数如下:</p>
<pre><code>import os
import tempfile
import pdfkit
from flask import render_template, make_response
@app.route('/generate_pdf')
def render_pdf_custom_header(foo, bar):
main_content = render_template('main_pdf.html', foo=foo)
options = {
'--encoding': "utf-8"
}
add_pdf_header(options, bar)
add_pdf_footer(options)
try:
pdf = pdfkit.from_string(main_content, False, options=options)
finally:
os.remove(options['--header-html'])
os.remove(options['--footer-html'])
response = build_response(pdf)
return response
def add_pdf_header(options, bar):
with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as header:
options['--header-html'] = header.name
header.write(
render_template('header.html', bar=bar).encode('utf-8')
)
return
def add_pdf_footer(options):
# same behaviour as add_pdf_header but without passing any variable
return
def build_response(pdf):
response = make_response(pdf)
response.headers['Content-Type'] = 'application/pdf'
filename = 'pdf-from-html.pdf'
response.headers['Content-Disposition'] = ('attachment; filename=' + filename)
return response
</code></pre>
<p>注意,我使用了<code>'--header-html'</code>和<code>'--footer-html'</code>符号,因为它与wkhtmltopf的<strong>选项格式匹配。</p>