Writing and formatting the content of a text file to a PDF file

1k Views Asked by At

I want to create PDF file and write text that I read from file. The text in the file looks like:

Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA
Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA
Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA

I created PDF with FPDF library. The code:

pdf = FPDF()

pdf.add_page()
pdf.set_font('Arial', 'B', 14)
pdf.text(0, 0 , text)

pdf.output(fileNameBase + ".pdf", "F")

The issue is the text is rendered in one line. So the text is not fully shown. I want to write text with the same format in text file. How can I create PDF file with the same format in the text file?

1

There are 1 best solutions below

2
User051209 On BEST ANSWER

Use multi_cell() method instead of text() method.
multi_cell or cell are directly recommended by the text() method documentation:

From text() method documentation:
text() method prints a character string. The origin is on the left of the first character, on the baseline. This method allows placing a string precisely on the page, but it is usually easier to use cell, multi_cell or write, which are the standard methods to print text.

To test your program I have created a text file called file.txt which contains your example text:

Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA
Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA
Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA

Changing your code to use multi_cell() and read the text message to write to the PDF file, from the text file file.txt, your program becomes:

from fpdf import FPDF
import webbrowser

fileNameBase = "question_so"

'''+++++++++++++++++++++++++++++++++++++++++++++++++++
Reads and returns the text contained into the file.txt 
+++++++++++++++++++++++++++++++++++++++++++++++++++'''
def get_file_content():
    text = ""
    with open('file.txt') as f:
        for line in f:
            text += line
    return text

def main():

    pdf = FPDF()

    pdf.add_page()
    pdf.set_font('Arial', 'B', 14)
    # I have commented your call to text() method
    #pdf.text(0, 0 , text)
    # read the content of the file
    text = get_file_content()
    pdf.multi_cell(w=210, h=6, txt=text, border=0, align='L', fill=False)

    pdf.output(fileNameBase + ".pdf", "F")
    webbrowser.open_new('question_so.pdf')

main()

By the execution of the function main() I get a PDF file called question_so.pdf with the content showed by the following image:

the PDF content