Pdfkit頁眉和頁腳 [英] pdfkit headers and footers
本文介紹了Pdfkit頁眉和頁腳的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我一直在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
結尾并手動刪除。
這篇關于Pdfkit頁眉和頁腳的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!
查看全文