Python 使用Django将参数设置为reportlab标头

Python 使用Django将参数设置为reportlab标头,python,django,reportlab,Python,Django,Reportlab,我正在根据生成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 heade

我正在根据生成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.
_页眉_页脚由以下函数调用:

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

如何将自定义数据变量发送到_header\u footer方法?

此处至少有两个选项:

可以使用它将一些参数“绑定”到函数。例如:

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\u 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()

接受,但是部分的,而不是部分:)@SébastienDeprez你用“部分”救了我