Python实现简单拆分PDF文件的方法

yipeiwu_com5年前Python基础

本文实例讲述了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文件

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获取时间及时间格式转换问题实例代码详解

整理总结一下python中最常用的一些时间戳和时间格式的转换 第一部分:获取当前时间和10位13位时间戳 import datetime, time '''获取当前时间''' n =...

Python中的字典与成员运算符初步探究

Python中的字典与成员运算符初步探究

Python元字典 字典(dictionary)是除列表以外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。 两者之间的区别在于:字典当中的元素是通...

pyqt实现.ui文件批量转换为对应.py文件脚本

大家都知道,在通过Pyqt4的designer工具创建界面.ui文件后需要手动cmd命令将.ui文件转换为.py之后才能进行事件的编写,如果遇到一次创建很多.ui文件一个个转换会很麻烦,...

python通过Windows下远程控制Linux系统

python通过Windows下远程控制Linux系统

一、学习目标 【通过Windows下远程控制Linux系统实现对socket模块认识】 二、实验环境 Windows下(模拟客户端 [ IP:192.168.43.87 ] ):pyth...

Python实现网站表单提交和模板

Python实现网站表单提交和模板

如果像前面那么做网站,也太丑陋了。并且功能也不多。 在实际做网站中,现在都要使用一个模板,并且在用户直接看到的页面,用html语言来写页面。 在做网站的行业里面,常常将HTML+CSS+...