1

我正在尝试使用 django-wkhtmltopdf 将 html 文件转换为 pdf。但是我无法将自定义变量与页眉和页脚一起使用,因为我没有找到确切的语法或正确的实现,而且我无法在 wkhtmltopdf v 0.12.5(已修补的 qt)中使用封面页它会引发错误未知的长论点--cover?

*VIEWS.PY*
from django.http import HttpResponse
from django.views.generic import View
from django.template.loader import get_template 
from django.template import Context
import pdfkit

class GeneratePdf(View):
    def get(self, request, *args, **kwargs):
        template = get_template("report.html")
        options = {
    'page-size': 'A4',
    'margin-top': '0.6in',
    'margin-right': '0.00in',
    'margin-bottom': '0.6in',
    'margin-left': '0.00in',
    'encoding': "UTF-8",
    'no-outline': None,
    'disable-smart-shrinking': False,

     'cover': 'cover.html',
    'header-html': 'header.html',
    'footer-html': 'footer.html',
    'header-spacing': 10,
    'footer-spacing': 5,
    'header-right': '[page]',
    }
    pdfkit.from_string(html, 'reports_demo.pdf', options=options)
    pdf = open("reports_demo.pdf")
    response = HttpResponse(pdf.read(), content_type='application/pdf') 
    return response
4

1 回答 1

1

您只需要为页眉和页脚设置单独的 html 文件。例如。

header.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
Code of your header goes here.

然后你就可以使用它了。

import pdfkit

pdfkit.from_file('path/to/your/file.html', 'out.pdf', {
    '--header-html': 'path/to/header.html'
})
于 2019-02-12T11:08:06.603 回答