Reputation: 13
I want to use the Python library fpdf2 and build my own class to generate a pdf document. 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.
# pdfinfo 1.pdf | grep Pages
Pages: 1
# pdfinfo 2.pdf | grep Pages
Pages: 1
Upvotes: -1
Views: 781
Reputation: 3121
you are mixin two concepts inheritance and composotion. 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:
Option1 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'
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:
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/
Upvotes: 0