I'm using the method multicell() of the class FPDF
(library PyFPDF) and, to manage it in my real application, I have to use the method get_string_width().
Description of my code
- The code below creates a PDF file called
multi_cell.pdf
. - Inside the PDF I have inserted only a multicell which contains the message:
Hello World! I'm trying to use multi_cell() method - The code implements also the function
get_num_of_lines_in_multicell(pdf, message)
which tries to calculate the number of lines the text is divided into the multicell. The function uses the method get_string_width() of the class FPDF.
The code and its output
from fpdf import FPDF
import webbrowser
CELL_WIDTH = 20
# function that calculates the number of lines inside multicel
def get_num_of_lines_in_multicell(pdf, message):
n = 1
msg_width = pdf.get_string_width(message)
while msg_width > n * CELL_WIDTH:
n += 1
return n
def main():
pdf=FPDF()
pdf.add_page()
pdf.set_font('Arial','',8)
cell_message1 = "Hello World! I'm trying to use multi_cell() method"
pdf.multi_cell(CELL_WIDTH, 4, cell_message1, 1, 0)
# call the function get_num_of_lines_in_multicell() and print the number of lines inside the multicell
print(f"num lines in the multi_cell = {get_num_of_lines_in_multicell(pdf, cell_message1)}")
# creation of the PDF
pdf.output('multi_cell.pdf','F')
# open the PDF
webbrowser.open_new('multi_cell.pdf')
main()
The output of the file on the standard output is the followed:
num lines in the multi_cell = 4
But the multicell inside the PDF file created contains the message on 5 LINES and not 4 LINES. Below I show the PDF content:
Question
Where is the error in the function get_num_of_lines_in_multicell(pdf, message)
which return 4 lines, while in the file created the lines are 5?