0

我是 Python 课程的新手,所以请帮帮我。我正在使用 fpdf 包生成 pdf 格式的报告。

我正在使用以下示例代码生成带页脚的 PDF 页面。

https://pyfpdf.readthedocs.io/en/latest/Tutorial/index.html#header-footer-page-break-and-image

from fpdf import FPDF

class PDF(FPDF):
    def header(self):
        # Logo
        self.image('logo_pb.png', 10, 8, 33)
        # Arial bold 15
        self.set_font('Arial', 'B', 15)
        # Move to the right
        self.cell(80)
        # Title
        self.cell(30, 10, 'Title', 1, 0, 'C')
        # Line break
        self.ln(20)

    # Page footer
    def footer(self):
        # Position at 1.5 cm from bottom
        self.set_y(-15)
        # Arial italic 8
        self.set_font('Arial', 'I', 8)
        # Page number
        self.cell(0, 10, 'Page ' + str(self.page_no()) + '/{nb}', 0, 0, 'C')

# Instantiation of inherited class
pdf = PDF()
pdf.alias_nb_pages()
pdf.add_page()
pdf.set_font('Times', '', 12)
for i in range(1, 5):
    pdf.cell(0, 10, 'Printing line number ' + str(i), 0, 1)
pdf.output('tuto2.pdf', 'F')

这会生成 5 页。我想在页脚中添加一个列表元素。

list=['A','B','C','D','E']
for i in range(1, 5):
    pdf.cell(0, 10, 'Printing line number ' + str(i)+list[i], 0, 1)
pdf.output('tuto2.pdf', 'F')

如何将此列表传递给班级?这个列表是在上面的类的派生类中生成的。

4

2 回答 2

0

我没有找到要测试的包,但是我添加了一个 init 来生成一个字母列表,这样您就可以在基于

"""
https://stackoverflow.com/questions/61473844/access-a-local-variable-via-class-method-in-python
https://stackoverflow.com/questions/453576/is-there-a-fast-way-to-generate-a-dict-of-the-alphabet-in-python
"""
from fpdf import FPDF
import string

class PDF(FPDF):
    def ___init___(self):
        letters = string.ascii_lowercase
        alphabet = d = dict(zip(range(1,27), letters))

    def header(self):
        # Logo
        self.image('logo_pb.png', 10, 8, 33)
        # Arial bold 15
        self.set_font('Arial', 'B', 15)
        # Move to the right
        self.cell(80)
        # Title
        self.cell(30, 10, 'Title', 1, 0, 'C')
        # Line break
        self.ln(20)

    # Page footer
    def footer(self):
        # Position at 1.5 cm from bottom
        self.set_y(-15)
        # Arial italic 8
        self.set_font('Arial', 'I', 8)
        # Page number
        self.cell(0, 10, 'Page ' + str(self.page_no()) + str(self.alphabet.get(self.page_no()) + '/{nb}', 0, 0, 'C')

if __name__ == '__main__':
    # Instantiation of inherited class
    pdf = PDF()
    pdf.alias_nb_pages()
    pdf.add_page()
    pdf.set_font('Times', '', 12)
    for i in range(1, 5):
        pdf.cell(0, 10, 'Printing line number ' + str(i), 0, 1)
    pdf.output('tuto2.pdf', 'F')
于 2020-04-28T07:38:14.100 回答
0

幸运的是,想通了!

class PDF1(FPDF,HTMLMixin):
    def __init__(self, list):
        super(PDF1, self).__init__()
        self.proper_name = list
于 2020-04-28T07:55:56.067 回答