我想创建PDF文件,并写文本,我从文件中读取.文件中的文本如下所示:

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

我用FPDF库创建了PDF.代码:

pdf = FPDF()

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

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

问题是文本呈现在一行中.因此,文本没有完全显示出来.我想在文本文件中写出相同格式的文本.如何创建与文本文件格式相同的PDF文件?

推荐答案

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文件,其内容如下:

the PDF content

Python相关问答推荐

比较两个二元组列表,NP.isin

在内部列表上滚动窗口

如何自动抓取以下CSV

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

即使在可见的情况下也不相互作用

try 与gemini-pro进行多轮聊天时出错

连接两个具有不同标题的收件箱

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

Python解析整数格式说明符的规则?

numpy卷积与有效

如何将多进程池声明为变量并将其导入到另一个Python文件

将9个3x3矩阵按特定顺序排列成9x9矩阵

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

迭代嵌套字典的值

如何保持服务器发送的事件连接活动?

与命令行相比,相同的Python代码在Companyter Notebook中运行速度慢20倍

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

从列表中获取n个元素,其中list [i][0]== value''

在Python中控制列表中的数据步长

文本溢出了Kivy的视区