如何在 Reportlab 中根据不同文档的信息生成 pdf?

How can I generate a pdf in Reportlab from information from different documents?

任何知道的人都可以帮助我了解这段代码如何工作以生成所需的页面。

c = canvas.Canvas("sample.pdf")
sample1 = csv.reader(open('sample1.csv'))
for i in sample1:
    first = i[0]
    c.drawString(100,800,first)
    sample2 = csv.reader(open('sample2.csv'))
    for x in sample2:
        sec = x[0]
        third = x[1]
        fourth = x[2]
        c.drawString(200,700,sec)
        c.drawString(200,600,third)
        c.drawString(200,500,fourth)
    c.showPage()
c.save()

实际上,它只成功打印了 sample2 中的文档和 sample1 中的项目的一页.... 我正在尝试从两个文档中提取信息以用于生成一个 pdf。

我不知道我是否理解问题,但我会在没有嵌套循环的情况下这样做

我假设样本 1 XYZ 中有三行,样本 2 中有三行 ABCDEFGHI

它创建三个页面 XYZ 和接下来的三个页面 ABCDEFGHI

from reportlab.pdfgen import canvas
import csv

c = canvas.Canvas("sample.pdf")

#sample1 = csv.reader(open('sample1.csv'))
#sample2 = csv.reader(open('sample2.csv'))
sample1 = ["X", "Y", "Z"]
sample2 = ["ABC", "DEF", "GHI"]

for a in sample1:
    c.drawString(100, 800, a[0])  # X / Y / Z
    c.showPage()

for b in sample2:
    c.drawString(200, 700, b[0])  # A / D / G
    c.drawString(200, 600, b[1])  # B / E / H
    c.drawString(200, 500, b[2])  # C / F / I
    c.showPage()

c.save()

但是如果您只想创建三个页面 X+ABCY+DEFZ+GHI 那么您需要 zip()

from reportlab.pdfgen import canvas
import csv

c = canvas.Canvas("sample.pdf")

#sample1 = csv.reader(open('sample1.csv'))
#sample2 = csv.reader(open('sample2.csv'))
sample1 = ["X", "Y", "Z"]
sample2 = ["ABC", "DEF", "GHI"]

for a, b in zip(sample1, sample2):
    c.drawString(100, 800, a[0])

    c.drawString(200, 700, b[0])
    c.drawString(200, 600, b[1])
    c.drawString(200, 500, b[2])

    c.showPage()

c.save()

顺便说一句:如果你需要九页

  • X+ABCX+DEFX+GHI
  • Y+ABCY+DEFY+GHI
  • Z+ABCZ+DEFZ+GHI

然后你必须在第二个循环中移动 drawString( a[0])showPage()

from reportlab.pdfgen import canvas
import csv

c = canvas.Canvas("sample.pdf")

#sample1 = csv.reader(open('sample1.csv'))
sample1 = ["X", "Y", "Z"]

for a in sample1:

    #sample2 = csv.reader(open('sample2.csv'))
    sample2 = ["ABC", "DEF", "GHI"]

    for b in sample2:
        c.drawString(100, 800, a[0])

        c.drawString(200, 700, b[0])
        c.drawString(200, 600, b[1])
        c.drawString(200, 500, b[2])

        c.showPage()

c.save()