import os
import tempfile
import pdfkit
from django.template.loader import render_to_string
def render_pdf(template, context, output, header_template=None):
"""
Simple function for easy printing of pdfs from django templates
Header template can also be set
"""
html = render_to_string(template, context)
options = {
'--load-error-handling': 'skip',
}
try:
if header_template:
with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as header_html:
options['header-html'] = header_html.name
header_html.write(render_to_string(header_template, context).encode('utf-8'))
return pdfkit.from_string(html, output, options=options)
finally:
# Ensure temporary file is deleted after finishing work
if header_template:
os.remove(options['header-html'])
改进@V Stoykov answer,因为它帮助我使用烧瓶,在烧瓶中使用自定义标题的渲染函数如下:
注意,我使用了
'--header-html'
和'--footer-html'
符号,因为它与wkhtmltopf的选项格式匹配。我只对页眉使用它,但我认为对页脚也一样。
头部需要有单独的html文件。
header.html标题
然后你可以在Python中这样使用它
如果您使用像Django这样的后端并希望使用模板,那么棘手的部分是您不能将头html作为呈现字符串传递。你需要一个文件。
这就是我用Django渲染pdf的方法。
在我的示例中,我创建了放置呈现内容的临时文件。重要的一点是,临时文件需要以
.html
结尾并手动删除。您可以在
header-center
的值中添加头相关问题 更多 >
编程相关推荐