2017-05-11 2 views
0

저는 매 n 페이지마다 PDF를 분할하는 방법을 배우려고합니다. 파일 1 : p.1-4, 파일 2 : p.5-8 등 내가하려고 해요PyPDF2를 사용하여 매 n 페이지마다 PDF를 분할하는 방법은 무엇입니까?

내 경우

나는 네 페이지를 각각 포함하는 여러 덩어리로 64P의 PDF를 분할 할 PyPDF2을 이해하지만 내 noobness이 나를 압도 : 나는 addPage를 사용하는 종류의 루프를하고 남아있는 페이지가 없습니다까지 파일을 작성해야 추측

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

?

+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}') 

희망이 있습니다.