Python实现简单拆分PDF文件的方法
本文实例讲述了Python实现简单拆分PDF文件的方法。分享给大家供大家参考。具体如下:
依赖pyPdf处理PDF文件
切分pdf文件
使用方法:
1)将要切分的文件放在input_dir目录下
2)在configure.txt文件中设置要切分的份数(如要切分4份,则设置part_num=4)
3)执行程序
4)切分后的文件保存在output_dir目录下
5)运行日志写在pp_log.txt中
P.S.本程序可以批量切割多个pdf文件
frompyPdfimportPdfFileWriter,PdfFileReader
importos
importtime
importsys
defpart_pdf(input_file,output_file,config_count,f_w,now,file_name):
file1=file(input_file,'rb')
pdf=PdfFileReader(file1)
pdf_pages_len=len(pdf.pages)
ifconfig_count<=pdf_pages_len:
ye=pdf_pages_len/config_count
lst_ye=pdf_pages_len%config_count
part_count=0
part_count_ye=0
forfeninrange(config_count):
part_count+=1
ifpart_count==config_count:
part_ye=ye+lst_ye
else:
part_ye=ye
write_pdf(pdf,part_count_ye,part_count_ye+part_ye,fen,output_file)
part_count_ye+=ye
else:
f_w.writelines('time:'+now+'filename:'+file_name+'status:part_num>pdfpages[error]\n')
sys.exit(1)
defwrite_pdf(pdf,part_count_ye,part_count_ye_end,fen,output_file):
out=PdfFileWriter()
forppinrange(part_count_ye,part_count_ye_end):
out.addPage(pdf.getPage(pp))
ous=file(output_file+'_'+str(fen+1)+'.pdf','wb')
out.write(ous)
ous.close()
defpdf_main():
f=open('configure.txt','r')
f_w=open('pp_log.txt','a')
now=time.strftime('%Y-%m-%d%H:%M:%S')
foriinf:
i_=i.strip()
aa=i_.split('=')[1]
ifi_.find('part_num=')!=-1andaa.isdigit():
config_count=int(aa)
else:
f_w.writelines('time:'+now+'status:part_numinconfigure.txtiserror[error]\n')
sys.exit(1)
files=os.listdir('input_dir/')
foreachinfiles:
input_file='input_dir/'+each
file_name=input_file[input_file.index('/'):input_file.index('.')]
output_file='output_dir/'+file_name
part_pdf(input_file,output_file,config_count,f_w,now,file_name)
f_w.writelines('time:'+now+'filename:'+file_name+'status:success\n')
pdf_main()
希望本文所述对大家的Python程序设计有所帮助。