Pdfkit页眉和页脚
原学程将引见Pdfkit页眉以及页足的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。
成绩描写
我一向在Web上搜刮应用pdfkit(python包装器)完成页眉以及页足的职员的示例,但是找没有就任何示例。
谁能展现1些怎样应用pdfkit python包装器完成wkhtmltopdf中的选项的示例?
推举谜底
我只对于页眉应用它,但是我以为它对于页足也1样。
您须要为题目应用零丁的html文件。
Header.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF⑻">
</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作为出现的字符串停止传播。您须要有1个文件。
这便是我用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⑻'))
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页眉以及页足的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。