我一直在使用Stack Overflow上的一些很好的答案来帮助解决我的问题,但遇到了障碍。
我要做什么
我到目前为止所拥有的
from PyPDF2 import PdfFileWriter, PdfFileReader
import io
import pandas as pd
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
# Read CSV into pandas dataframe and assign columns as variables
csv = '/myfilepath/test.csv'
df = pd.read_csv(csv)
Name = df['First Name'].values + " " + df['Last Name'].values
OrderID = df['Order Number'].values
packet = io.BytesIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.setFont("Helvetica", 12)
if OrderID is not None:
can.drawString(80, 655, '#' + str(OrderID)[1:-1])
can.setFont("Helvetica", 16)
if Name is not None:
can.drawString(315, 630, str(Name)[2:-2]
can.save()
# move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(open("Unique1.pdf", "rb"))
output = PdfFileWriter()
# add the new pdf to the existing page
page = existing_pdf.getPage(0)
page2 = new_pdf.getPage(0)
page.mergePage(page2)
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("Output.pdf", "wb")
output.write(outputStream)
outputStream.close()
以上代码在以下情况下适用:
我需要什么帮助
附加信息:唯一的PDF将包含在一个文件夹中,因为它们各自具有相同的布局,但条形码不同
任何帮助将不胜感激!
答案 0 :(得分:0)
我个人建议您重新考虑使用Pandas,而应尝试使用标准CSV模块。它将满足您通过文件流进行逐行处理的需求。下面显示的是一些代码,循环遍历CSV文件,将每一行作为字典,并在write_pdf
函数中进行处理,以及将使您获得新文件名的逻辑,用于为每一行写入PDF。 / p>
import csv
# import the PDF libraries you need
def write_pdf(data, filename):
name = data['First Name'] + ' ' + data['Last Name']
order_no = data['Order Number']
# Leaving PDF writing to you
row_counter = 0
with open('file.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
write_pdf(row, 'Output' + row_counter + '.pdf')
row_counter += 1
我将把PDF写给您,因为我认为您比我更了解您的需求。
我知道我切除了Pandas部分,但是问题在于,对于多于1行的CSV,它如何不起作用,源于DataFrame.get
是一个检索整列。