Python實現簡單拆分PDF文件的方法
更新時間:2015年07月30日 12:09:04 作者:willzhao
這篇文章主要介紹了Python實現簡單拆分PDF文件的方法,可實現將一個PDF文件拆分成指定份數的功能,涉及pyPdf模塊的使用技巧,需要的朋友可以參考下
本文實例講述了Python實現簡單拆分PDF文件的方法。分享給大家供大家參考。具體如下:
依賴pyPdf處理PDF文件
切分pdf文件
使用方法:
1)將要切分的文件放在input_dir目錄下
2)在configure.txt文件中設置要切分的份數(如要切分4份,則設置part_num=4)
3)執(zhí)行程序
4)切分后的文件保存在output_dir目錄下
5)運行日志寫在pp_log.txt中
P.S. 本程序可以批量切割多個pdf文件
from pyPdf import PdfFileWriter, PdfFileReader
import os
import time
import sys
def part_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)
if config_count <= pdf_pages_len:
ye = pdf_pages_len / config_count
lst_ye = pdf_pages_len % config_count
part_count = 0
part_count_ye = 0
for fen in range(config_count):
part_count += 1
if part_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+' file name: '+file_name+' status: part_num > pdf pages [error]\n')
sys.exit(1)
def write_pdf(pdf, part_count_ye, part_count_ye_end, fen, output_file):
out = PdfFileWriter()
for pp in range(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()
def pdf_main():
f = open('configure.txt', 'r')
f_w = open('pp_log.txt', 'a')
now = time.strftime('%Y-%m-%d %H:%M:%S')
for i in f:
i_ = i.strip()
aa = i_.split('=')[1]
if i_.find('part_num=') != -1 and aa.isdigit():
config_count = int(aa)
else:
f_w.writelines('time: '+now+' status: part_num in configure.txt is error [error]\n')
sys.exit(1)
files = os.listdir('input_dir/')
for each in files:
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+' file name: '+file_name+' status: success\n')
pdf_main()
希望本文所述對大家的Python程序設計有所幫助。
相關文章
python常見問題之ModuleNotFoundError: No module nam
這篇文章主要介紹了python常見問題之ModuleNotFoundError: No module named ‘rest_framework‘解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-07-07

