SoFunction
Updated on 2024-11-19

Python method to achieve a simple split PDF file

In this paper, an example of Python to achieve a simple method of splitting PDF files. Shared for your reference. Specifically as follows:

Rely on pyPdf to process PDF files
Slicing pdf files

Usage:
1) Place the file to be sliced in the input_dir directory
2) Set the number of copies to be cut in the file (e.g., to cut 4 copies, set part_num=4)
3) Enforcement procedures
4) The sliced file is saved in the output_dir directory
5) Run logs are written in pp_log.txt

. This program can batch cut multiple pdf files

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()
  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')
    (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):
    ((pp))
  ous = file(output_file+'_'+str(fen+1)+'.pdf', 'wb')
  (ous)
  ()
def pdf_main():
  f = open('', 'r')
  f_w = open('pp_log.txt', 'a')
  now = ('%Y-%m-%d %H:%M:%S')
  for i in f:
    i_ = ()
    aa = i_.split('=')[1]
    if i_.find('part_num=') != -1 and ():
      config_count = int(aa)
    else:
      f_w.writelines('time: '+now+' status: part_num in  is error [error]\n')
      (1)
  files = ('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()

I hope that what I have described in this article will help you in your Python programming.