问题描述
我一直在Web上搜索使用pdfkit(python包装器)实现页眉和页脚的人员的示例,但找不到任何示例。
谁能展示一些如何使用pdfkit python包装器实现wkhtmltopdf中的选项的示例?
推荐答案
我只对页眉使用它,但我认为它对页脚也一样。
您需要为标题使用单独的html文件。
Header.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> Code of your header goes here. </body> </html>
然后您可以像在Python中那样使用它
import pdfkit pdfkit.from_file('path/to/your/file.html', 'out.pdf', { '--header-html': 'path/to/header.html' })
如果您使用像Django这样的后端并希望使用模板,那么棘手的部分是您不能将头html作为呈现的字符串进行传递。您需要有一个文件。
这就是我用Django呈现PDF的方法。
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'])在我的示例中,我创建了临时文件,将呈现的内容放在其中。重要部分是临时文件需要以.html结尾并手动删除。