Reputation: 10182
I have the below code that attempts to create a dictionary from a CSV file, then append the values from each "row" in the CSV to a new page within a PDF. I am using pyPdf and ReportLab to accomplish this.
The source PDF contains 2 pages, the front and back of a postcard, which I am trying to duplicate for each record within the CSV file. For example, a CSV file with 25 records would result in a PDF containing 50 pages. (One front and one back for each record)
I have succeeded in creating the PDF with the appropriate number of pages, however, the section of my code that is meant to append the values from the CSV file is appending the same same value for each page, rather than a unique value per page.
I am pretty sure this has to do with the loop since printing the dictionary returns all of the key and value pairs correctly. What have I done wrong here?
d = {}
csv_file = open(filename, 'rb')
reader = csv.reader(csv_file)
rownum = 0
for row in reader:
total_rows += 1
page_count = (total_rows - 1)
if rownum == 0:
header = row
else:
colnum = 0
for col in row:
d[header[colnum]] = col
colnum += 1
packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=(621,405))
can.drawString(340, 147, d['FirstName'])
can.save()
packet.seek(0)
new_pdf = PdfFileReader(packet)
existing_pdf = PdfFileReader(file(order, 'rb'))
output = PdfFileWriter()
front = existing_pdf.getPage(0)
back = existing_pdf.getPage(1)
back.mergePage(new_pdf.getPage(0))
for i in range(0, page_count):
output.addPage(front)
output.addPage(back)
outputStream = file(token+'_merged.pdf', 'wb')
output.write(outputStream)
outputStream.close()
rownum += 1
Upvotes: 0
Views: 184
Reputation: 37319
This loop creates a new file for each row in the CSV, overwriting the versions created for earlier rows. I am not entirely familiar with the libraries you're using, but it looks like an approach that moves the saving of the outputStream
outside the main loop would fix it:
output = PdfFileWriter()
for rownum, row in enumerate(reader):
if rownum == 0:
header = row
else:
for col in row:
d[header[colnum]] = col
colnum += 1
# or, more concisely:
# d = dict((header[colnum], value) for (colnum, value) in enumerate(row))
# or use a dict comprehension if you're on a sufficiently recent version
# or best of all, use a csv.DictReader object instead of creating the dictionary yourself
packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=(621,405))
can.drawString(340, 147, d['FirstName'])
can.save()
packet.seek(0)
new_pdf = PdfFileReader(packet)
# I would check whether this can be read once and still have getPage called multiple times
existing_pdf = PdfFileReader(file(order, 'rb'))
front = existing_pdf.getPage(0)
back = existing_pdf.getPage(1)
back.mergePage(new_pdf.getPage(0))
output.addPage(front)
output.addPage(back)
outputStream = file(token+'_merged.pdf', 'wb')
output.write(outputStream)
outputStream.close()
Upvotes: 1