pdfkit页眉和页脚

use*_*835 2 python pdfkit wkhtmltopdf

我一直在网上搜索使用pdfkit(python包装器)实现页眉和页脚的人的例子,但找不到任何例子.
有人能够使用pdfkit python包装器展示如何在wkhtmltopdf中实现选项的一些示例吗?

VSt*_*kov 10

我只使用它与标题,但我认为它将与页脚一样.

您需要为标题分别使用html文件.

了header.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>

    Code of your header goes here.

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

然后你可以在Python中使用它

import pdfkit

pdfkit.from_file('path/to/your/file.html', 'out.pdf', {
    '--header-html': 'path/to/header.html'
})
Run Code Online (Sandbox Code Playgroud)

如果您使用像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'])
Run Code Online (Sandbox Code Playgroud)

在我的示例中,我创建了临时文件,其中放置了渲染内容.重要的是临时文件需要.html手动结束和删除.