Use multi_cell() method instead of text()
method.
multi_cell
or cell
are 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.
为了测试您的程序,我创建了一个名为file.txt
的文本文件,其中包含示例文本:
Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA
Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA
Hello World. This is test text.
ASDFASDFAAAAAAAAAAAAAAAAAAAAAAA
如果我将您的代码更改为使用multi_cell()
,并从文本文件file.txt
中读取PDF文件的文本消息,则您的程序将变为:
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 comment 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()
通过执行函数main()
,我得到一个名为question_so.pdf
的PDF文件,其内容如下: