如何将输出数据写入pdf?

How to write output data into pdf?

我在 python 中找不到将输出数据(列表或函数 return)写入 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。但是你没有得到你 "want" 的结果,因为你的 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")