python – 使用Django报告标头的参数

我正在根据this example生成PDF并且工作正常,但是我在标题部分有一点问题,这是实际的代码:

def _header_footer(canvas, doc):
    # Save the state of our canvas so we can draw on it
    canvas.saveState()
    styles = getSampleStyleSheet()

    # Header
    header = Paragraph('This is a multi-line header.  It goes on every page.   ' * 5, styles['Normal'])
    w, h = header.wrap(doc.width, doc.topMargin)
    header.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - h)

    # Release the canvas
    canvas.restoreState()

我想将数据从模型发送到标题,就像这样

def _header_footer(canvas, doc, custom_data):
    canvas.saveState()
    styles = getSampleStyleSheet()

    header = Paragraph('This is my %s' % custom_data')

    #etc.

_header_footer被调用:

doc.build(elements, onFirstPage=self._header_footer, onLaterPages=self._header_footer)

如何将custom_data变量发送到_header_footer方法?

解决方法:

这里至少有两个选项:

您可以使用partial from functools,它允许将某些参数“绑定”到您的函数中.例如:

from functools import partial
def _header_footer(canvas, doc, custom_data):
    ...

# Usage:
doc.build(elements, onFirstPage=partial(_header_footer, custom_data=my_custom_data))

或者因为你似乎在一个类中使用它,由于self关键字(或者它是一个错字?),你可以简单地将custom_data作为你的类的属性.

class MyPdf(object):
    def __init__(self, custom_data):
        self.custom_data = custom_data
        self.doc = ... # your doc

    def _header_footer(self, canvas, doc):
        # you can access self.custom_data here
        ...

    def build(self):
        ...
        self.doc.build(elements, onFirstPage=self._header_footer)

# Usage
my_pdf = MyPdf(custom_data)
my_pdf.build()
上一篇:python – 将支持页面布局的水平线添加到ReportLab表布局


下一篇:为什么python双引号在文件名中转换为连字符?