Would anybody who knows, help me understand how this code can work to produce the required page.
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()
As it is, it prints only the documents in sample2 successfully and one page of the items in sample1.... I'm trying to extract information from two documents to use in generating one pdf.
I don't know if I understand problem but I would do this without nesting loops
I assum you have three rows in sample1 X
, Y
, Z
and three rows in sample2 ABC
, DEF
, GHI
It creates three pages X
, Y
, Z
and next three pages ABC
, DEF
, GHI
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()
But if you want to create only three pages X+ABC
, Y+DEF
, Z+GHI
then you need 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()
BTW: If you need nine pages
X+ABC
, X+DEF
, X+GHI
Y+ABC
, Y+DEF
, Y+GHI
Z+ABC
, Z+DEF
, Z+GHI
then you have to move drawString( a[0])
and showPage()
inside second loop
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()