【问题标题】:how to use custom variables in header/footer wkhtmltopdf for django?如何在 django 的页眉/页脚 wkhtmltopdf 中使用自定义变量?
【发布时间】:2019-02-12 11:02:01
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 你解决了吗?我在使用 Laravel 而不是 Django 时遇到了同样的问题。

标签: django wkhtmltopdf django-wkhtmltopdf


【解决方案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'
})

【讨论】:

  • 页眉和页脚正在工作,但我无法使用自定义变量。表示我无法传递动态数据。
  • 他要的是 wkhtmltopdf 但你要的是 pdfkit 解决方案。
猜你喜欢
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
相关资源
最近更新 更多