Python實(shí)現(xiàn)簡(jiǎn)單拆分PDF文件的方法
本文實(shí)例講述了Python實(shí)現(xiàn)簡(jiǎn)單拆分PDF文件的方法。分享給大家供大家參考。具體如下:
依賴pyPdf處理PDF文件
切分pdf文件
使用方法:
1)將要切分的文件放在input_dir目錄下
2)在configure.txt文件中設(shè)置要切分的份數(shù)(如要切分4份,則設(shè)置part_num=4)
3)執(zhí)行程序
4)切分后的文件保存在output_dir目錄下
5)運(yùn)行日志寫在pp_log.txt中
P.S. 本程序可以批量切割多個(gè)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()
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python實(shí)現(xiàn)多線程HTTP下載器示例
本篇文章主要介紹了Python實(shí)現(xiàn)多線程HTTP下載器示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02
Async?IO在Python中的異步編程工作實(shí)例解析
這篇文章主要為大家介紹了Async?IO在Python中的異步編程工作實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Python實(shí)現(xiàn)json對(duì)值進(jìn)行模糊搜索的示例詳解
我經(jīng)常使用json進(jìn)行存儲(chǔ)配置,于是常常遇到這樣的問題:如果想要對(duì)某個(gè)數(shù)組里的值進(jìn)行模糊搜索,同時(shí)輸出相關(guān)的其他數(shù)組相同位置的的值該如何實(shí)現(xiàn)呢?本文就來和大家詳細(xì)聊聊2023-01-01
Python實(shí)現(xiàn)對(duì)照片中的人臉進(jìn)行顏值預(yù)測(cè)
今天給大家?guī)淼氖顷P(guān)于Python實(shí)戰(zhàn)的相關(guān)知識(shí),文章圍繞如何用Python實(shí)現(xiàn)對(duì)照片中的人臉進(jìn)行顏值預(yù)測(cè)展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
python常見問題之ModuleNotFoundError: No module nam
這篇文章主要介紹了python常見問題之ModuleNotFoundError: No module named ‘rest_framework‘解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-07-07

