使用 PyPDF2 将字符串写入 pdf

Ped*_*ski 7 pdf python-3.x

我将用 Python 读取 130 多个 excel 文件作为字符串行。我想将每一行写入pdf。整个Excel文件只是一张A5横向纸。我可以轻松地在 bash shell 中批量打印 pdf。

我导入 PyPDF2

我可以使用以下命令创建 pdf 或一系列 pdf 文件:

with open(path + fileName, 'wb') as out:
        pdf_writer.write(out)
Run Code Online (Sandbox Code Playgroud)

但我太笨了,不知道如何向这个 pdf 中写入字符串。如果我尝试编写字符串变量,我只会收到错误。如果我将字符串转换为字节,我只会收到错误。

如何将字符串放入我的 pdf 中?

string = '任何旧字符串'

Fab*_*ian 4

我知道您要求PyPDF2更简单的方法FPDF

# https://pyfpdf.readthedocs.io/en/latest/
import fpdf #pip3 intall fpdf

pdf = fpdf.FPDF(format='letter') #pdf format
pdf.add_page() #create new page
pdf.set_font("Arial", size=12) # font and textsize
pdf.cell(200, 10, txt="your text", ln=1, align="L")
pdf.cell(200, 10, txt="your text", ln=2, align="L")
pdf.cell(200, 10, txt="your text", ln=3, align="L")
pdf.output("test.pdf")
Run Code Online (Sandbox Code Playgroud)

正如您提到的,您不明白,PyPDF 文档非常好,所以我认为FPDF这是一个好的开始。

PyPDF2更适合阅读和合并pdf文件。

如果您确实喜欢使用 PyPDF2,您可以使用canvas.