2017-05-11 3 views
0

私は、nページごとにpdfを分割する方法を学ぼうとしています。私の場合はPyPDF2を使ってnページごとにPDFを分割する方法は?

私は4ページごとを含むいくつかのチャンクに64PのPDFを分割したい:ファイル1:p.1-4、ファイル2:P.5-8など

私がしようとしていますPyPDF2を理解するが、私のnoobnessは私を圧倒する:

from PyPDF2 import PdfFileWriter, PdfFileReader 
pdf = PdfFileReader('my_pdf.pdf') 

私はaddPageを使用しての種類のループを作り、残されたページはありませんまでのファイルを記述する必要が推測?

+0

あなたはまだこの質問に興味がありますか? – Henry

+0

はい、非常にそうです。 – Buschmann

答えて

0

少し遅れてしまいましたが、私は同じことをやろうとしているときに助けを求めている間にあなたの質問に走りました。 私はあなたが求めていることをして、次のことをやりました。おそらくそれはあなたが求めている以上のものですが、答えはそこにあります。これは、リファクタリングといくつかの変数の名前変更が必要なため、大まかな最初のドラフトです。

import os 
from PyPDF2 import PdfFileReader, PdfFileWriter 

def split_pdf(in_pdf, step=1): 
    """Splits a given pdf into seperate pdfs and saves 
    those to a supfolder of the parent pdf's folder, called 
    splitted_pdf. 

    Arguments: 
     in_pdf: [str] Absolute path (and filename) of the 
       input pdf or just the filename, if the file 
       is in the current directory. 
     step: [int] Desired number of pages in each of the 
       output pdfs. 
    Returns: 
     dunno yet 
    """ 
    #TODO: Add choice for output dir 
    #TODO: Add logging instead of prints 
    #TODO: Refactor 
    try:  
     with open(in_pdf, 'rb') as in_file: 
      input_pdf = PdfFileReader(in_file) 
      num_pages = input_pdf.numPages 
      input_dir, filename = os.path.split(in_pdf) 
      filename = os.path.splitext(filename)[0] 
      output_dir = input_dir + "/" + filename + "_splitted/" 
      os.mkdir(output_dir) 
      intervals = range(0, num_pages, step) 
      intervals = dict(enumerate(intervals, 1)) 
      naming = f'{filename}_p' 

      count = 0 
      for key, val in intervals.items(): 
       output_pdf = PdfFileWriter() 
       if key == len(intervals): 
        for i in range(val, num_pages): 
         output_pdf.addPage(input_pdf.getPage(i)) 
        nums = f'{val + 1}' if step == 1 else f'{val + 1}-{val + step}' 
        with open(f'{output_dir}{naming}{nums}.pdf', 'wb') as outfile: 
         output_pdf.write(outfile) 
        print(f'{naming}{nums}.pdf written to {output_dir}') 
        count += 1 
       else: 
        for i in range(val, intervals[key + 1]): 
         output_pdf.addPage(input_pdf.getPage(i)) 
        nums = f'{val + 1}' if step == 1 else f'{val + 1}-{val + step}' 
        with open(f'{output_dir}{naming}{nums}.pdf', 'wb') as outfile: 
         output_pdf.write(outfile) 
        print(f'{naming}{nums}.pdf written to {output_dir}') 
        count += 1 
    except FileNotFoundError as err: 
     print('Cannot find the specified file. Check your input:') 
    print(f'{count} pdf files written to {output_dir}') 

希望します。

関連する問題