简体   繁体   English

为 FPDF 构建 Python class

[英]Build a Python class for FPDF

I want to use the Python library fpdf2 and build my own class to generate a pdf document.我想使用 Python 库fpdf2并构建我自己的 class 来生成 pdf 文档。 I tried this:我试过这个:

from fpdf import FPDF   

class MyPdf(FPDF):
    def __init__(self, *args, **kwargs):
            super().__init__()
            self.pdf = FPDF()
            self.pdf.add_page()
            # customize pdf
    def OtherCustomization(self):
            self.pdf.add_page()
            # other customization pdf


pdf1 = FPDF()
pdf1.add_page()

pdf2 = MyPdf()
pdf2.add_page()
pdf2.OtherCustomization()

pdf1.output("1.pdf")
pdf2.output("2.pdf")

I expect a file 1.pdf with one page, another 2.pdf with two pages, but it does not work.我希望文件 1.pdf 有一页,另一个 2.pdf 有两页,但它不起作用。

# pdfinfo 1.pdf | grep Pages
Pages:           1
# pdfinfo 2.pdf | grep Pages
Pages:           1

you are mixin two concepts inheritance and composotion.你混合了两个概念 inheritance 和组合。 when you use inherintance you do not need to add a class instance as an attribute, since all attributes or methods of the parent class are also from the child class:当您使用继承时,您不需要添加 class 实例作为属性,因为父 class 的所有属性或方法也来自子 class:

Option1 Inheritance:选项 1 Inheritance:

from fpdf import FPDF   

class MyPdf(FPDF):
    def __init__(self, *args, **kwargs):
            super().__init__()
            
            # customize pdf
    def OtherCustomization(self):
            self.add_page()
            # other customization pdf

pdf1 = MyPdf()
pdf1.add_page()

In option1 one you can modify properties of your child class for example you can force you page to be always horizontal in your child class when you pass to the constructor page_orientation='L'在选项 1 中,您可以修改孩子 class 的属性,例如,当您传递给构造函数page_orientation='L'时,您可以强制页面在孩子 class 中始终保持水平

from fpdf import FPDF   

class MyHorizontalPdf(FPDF):
    def __init__(self,value, format="A4",  *args, **kwargs):
            super().__init__(page_orientation='L', format=format)
            self.value = value
            # customize pdf
    def OtherCustomization(self):
            self.add_page()
            # other customization pdf

Option2 Composition:选项2组成:

from fpdf import FPDF   

class MyPdf:
    def __init__(self, *args, **kwargs):
            self.pdf = FPDF()
            # customize pdf
    def OtherCustomization(self):
            self.pdf.add_page()
            # other customization pdf

pdf1 = MyPdf()
pdf1.pdf.add_page()
class MyHorizontalPdf:
    def __init__(self, *args, **kwargs):
            self.pdf = FPDF(page_orientation='L')
            # customize pdf
    def OtherCustomization(self):
            self.pdf.add_page()
            # other customization pdf

I will advice to read more here https://realpython.com/inheritance-composition-python/我建议在这里阅读更多内容 https://realpython.com/inheritance-composition-python/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM