python - 如何将输出数据写入pdf?

标签 python pdf fpdf

我找不到在 python 中将输出数据(列表或函数返回)写入 pdf 的方法。这是我的简单代码。我想在pdf中逐行编写数据列表的i。但输出仅显示 [1,2,3,4,5,6]。 哪个 pdf 模块更适合我使用?

import fpdf

data=[1,2,3,4,5,6]

pdf = fpdf.FPDF(format='letter')
pdf.add_page()
pdf.set_font("Arial", size=12)

for i in str(data):
    pdf.write(5,i)
pdf.output("testings.pdf")

最佳答案

您所做的一切都是正确的,可以将输出写入 PDF。但是您没有得到您“想要”的结果,因为您的 Python 代码不正确!

for i in str(data):
      <em>.. do stuff with <strong>i</strong> here ..</em>

并没有按照您的想法行事。一旦将 data 转换为字符串,根据 str(data),它就会神奇地变成字符串

[1, 2, 3, 4, 5, 6]

然后 for 循环遍历该字符串的内容——它的字符——并将它们一个一个地写入 PDF。

这是你的第一个错误。是的,您必须为 pdf.write 提供一个字符串——但只是您要写入的每个单独项目,而不是整个输入对象。

第二个假设 pdf.write 输出一行末尾包含 return。它不会:

This method prints text from the current position. When the right margin is reached (or the \n character is met), a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text.
(https://pyfpdf.readthedocs.io/en/latest/reference/write/index.html)

您可以使用 ln插入换行符,或在写入每个字符串的末尾附加 \n

工作代码:

import fpdf

data=[1,2,3,4,5,6]

pdf = fpdf.FPDF(format='letter')
pdf.add_page()
pdf.set_font("Arial", size=12)

for i in data:
    pdf.write(5,str(i))
    pdf.ln()
pdf.output("testings.pdf")

关于python - 如何将输出数据写入pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355443/

相关文章:

python - python shell中的默认函数

python - 有没有办法在元组/列表列表中添加索引?

c# - 在 C# 中加载用 python 构建的 keras 模型?

asp.net-mvc-3 - 带 pdf 的 mvc 3 页面 - 滚动条/已加载

php - FPDF SetX 和 SetY 调用顺序错误?

php - 如何使用 fpdf 在分页符上重复标题

python - 使用scrapy抓取动态内容

google-chrome - 使用 Chrome pdfium 将 HTML 转换为 PDF

pdf - jsPDF自动表格宽列内容不会中断

python - PyFPDF 在编码为字节字符串后返回空白 pdf