Search code examples
pythonfpdf

FPDF writes to only one line


The variable "output" in the code below is a couple of paragraphs of text and I am trying to write it all to a pdf using FPDF. But, it writes to only one line. How do I get it to include line breaks. For example, the text has "\n" in several locations of the text but its ignored. Thank you.

dummytext = "line 1" + "\n"
dummytext += "line 2" + "\n"
dummytext += "line 3"

pdf = FPDF()
pdf.add_page()
pdf.set_xy(0,0)
pdf.set_font('arial', 'B', 13.0)
pdf.cell(ln=0, h=5.0, align='L', w=0, txt=dummytext, border=0)
pdf.output('testpdf.pdf', 'F')

The variable dummytext shows up in the pdf as:

line 1 line 2 line 3

Solution

  • Using multi_cell will facilitate the new lines in FPDF output.

    multi_cell: This method allows printing text with line breaks.

    Details can be found in Documentation of multi_cell.

    code.py:

    from fpdf import FPDF
    dummytext = "line 1" + "\n"
    dummytext += "line 2" + "\n"
    dummytext += "line 3"
    pdf = FPDF()
    pdf.add_page()
    pdf.set_xy(0,0)
    pdf.set_font('arial', 'B', 13.0)
    pdf.multi_cell(0, 5, dummytext)
    pdf.output('testpdf.pdf', 'F')
    

    Output:

    fpdf newline in output