熬夜肝的。先贴代码:
# -*- coding: utf-8 -*-
import pandas as pd
import pdfrw
Excel_path = 'C:\\Users\\sayer\\Desktop\\ASD\\a4.xlsx'
#i = 1
#INVOICE_TEMPLATE_PATH = 'C:\\Users\\sayer\\Desktop\\ASD\\a4.pdf'
#INVOICE_OUTPUT_PATH = 'C:\\Users\\sayer\\Desktop\\ASD\\output\\a%s.pdf'%(i)
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
template_pdf = pdfrw.PdfReader(input_pdf_path)
annotations = template_pdf.pages[0][pdfrw.PdfName.Annots]
for annotation in annotations:
if annotation[pdfrw.PdfName.Subtype] == pdfrw.PdfName.Widget:
if annotation[pdfrw.PdfName.T]:
key = annotation[pdfrw.PdfName.T][1:-1]
if key in data_dict.keys():
annotation.update(
pdfrw.PdfDict(V='{}'.format(data_dict[key]))
)
pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
print("Hi!")
for i in range(【行数】):
INVOICE_TEMPLATE_PATH = 'C:\\Users\\sayer\\Desktop\\ASD\\tianxie.pdf'
#INVOICE_OUTPUT_PATH = 'C:\\Users\\sayer\\Desktop\\ASD\\output\\a%s.pdf'%(i)
df = pd.read_excel(Excel_path)
data_dict = df.iloc[i].to_dict()
print(data_dict)
INVOICE_OUTPUT_PATH = 'C:\\Users\\sayer\\Desktop\\ASD\\output\\%s.pdf'%(str(i+1)+data_dict["xm1"])
write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)
print("out")
#df = pd.read_excel(Excel_path)
#data_dict = df.iloc[1].to_dict()
#print(data_dict)
#write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)
后续更新:又更新了一下代码:
# -*- coding: utf-8 -*-
import pandas as pd
import pdfrw
Excel_path = './sheet.xlsx'
hangshu = input("一共有多少人呢?")
hangshu = int(hangshu)
#i = 1
#INVOICE_TEMPLATE_PATH = 'C:\\Users\\sayer\\Desktop\\ASD\\a4.pdf'
#INVOICE_OUTPUT_PATH = 'C:\\Users\\sayer\\Desktop\\ASD\\output\\a%s.pdf'%(i)
def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
template_pdf = pdfrw.PdfReader(input_pdf_path)
annotations = template_pdf.pages[0][pdfrw.PdfName.Annots]
for annotation in annotations:
if annotation[pdfrw.PdfName.Subtype] == pdfrw.PdfName.Widget:
if annotation[pdfrw.PdfName.T]:
key = annotation[pdfrw.PdfName.T][1:-1]
if key in data_dict.keys():
annotation.update(
pdfrw.PdfDict(V='{}'.format(data_dict[key]))
)
pdfrw.PdfWriter().write(output_pdf_path, template_pdf)
print("Start Working.")
for i in range(hangshu):
INVOICE_TEMPLATE_PATH = './moban.pdf'
#INVOICE_OUTPUT_PATH = 'C:\\Users\\sayer\\Desktop\\ASD\\output\\a%s.pdf'%(i)
df = pd.read_excel(Excel_path)
data_dict = df.iloc[i].to_dict()
print(data_dict)
INVOICE_OUTPUT_PATH = './output/%s.pdf'%(str(i+1)+data_dict["xm1"])
write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)
print("Success.")
#df = pd.read_excel(Excel_path)
#data_dict = df.iloc[1].to_dict()
#print(data_dict)
#write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)