Search code examples
pythonpython-3.xpyfpdf

What does the value that pdf.w returns mean and how does the method work in PyFPDF


I've been using the PyFPDF library for a while now, and when I was looking at other programmers codes I encountered a method that looks like this: (mostly It was used to set the width of columns in a table)

from fpdf import FPDF
pdf = FPDF()
pdf.w

I checked what doest the pdf.w method returns and it gives me a float number equal to 210.0015555555555. I'm wondering what does this method do and what does the float number mean centimieters, millimeters, pixels or something else?

I've printed the value of pdf.w and can't figure out what does it mean.


Solution

  • As one of @Barmar's comments says, if you try to execute the following code, you obtain the width of the page (and not of the cell of a table) in the different unit of measure (mm, cm, inch, point):

    from fpdf import FPDF
    
    # default unit of measure is mm
    pdf = FPDF()
    print(f"Width Page = {pdf.w} mm (default unit of measure)")
    
    pdf = FPDF(unit='mm')
    print(f"Width Page = {pdf.w} mm")
    
    pdf = FPDF(unit="cm")
    print(f"Width Page = {pdf.w} cm")
    
    pdf = FPDF(unit="pt")
    print(f"Width Page = {pdf.w} point")
    
    pdf = FPDF(unit="in")
    print(f"Width Page = {pdf.w} inch")
    

    The output of the execution of the previous code is:

    Width Page = 210.0015555555555 mm (default unit of measure)
    Width Page = 210.0015555555555 mm
    Width Page = 21.000155555555555 cm
    Width Page = 595.28 pt
    Width Page = 8.267777777777777 inch
    

    For details see the documentation of the class FPDF.

    The width of a column

    To build a table by PyFPDF you have to add a cell or multi_cell one after the other and set the attibute w of the cell or multi_cell when you construct these objects:

    from fpdf import FPDF
    
    # unit of measure is mm => for the cell width too
    pdf = FPDF()
    
    pdf.set_font('Times')
    pdf.add_page()
    
    # set width of the cell = 10 mm
    pdf.cell(w=10, h=5, txt='value', border=1)
    
    # set width of the multicell_cell = 100 mm
    pdf.multi_cell(w=100, h=5, txt='multicell value', border=1)