티스토리 뷰

PDF 분할과 PyMuPDF Pro

문서 처리 업무에서 PDF 파일을 다루는 일은 매우 흔한데요,
그중에서도 여러 페이지로 구성된 PDF를 페이지별 개별 파일로 나누는 작업은 특히 자주 하게됩니다.
PyMuPDF Pro는 이러한 작업을 쉽고 빠르게 처리할 수 있는 강력한 파이썬 라이브러리입니다.


PyMuPDF Pro란?

PyMuPDF Pro는 MuPDF라는 경량 PDF 엔진을 파이썬에서 사용할 수 있도록 만든 라이브러리입니다.
PDF 문서를 읽기, 작성, 편집, 가공하는 다양한 기능을 제공하며, 속도와 안정성이 뛰어나 PDF 작업에 널리 사용됩니다.


설치 방법

PyMuPDF Pro는 pip 명령어로 간단히 설치할 수 있습니다.

pip install PyMuPDF​

💡기본 PDF 분할

아래는 하나의 PDF 파일을 페이지별로 나누어 저장하는 간단한 함수 예제입니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import pymupdf
 
def split_pdf_to_pages(input_path, output_folder):
    """
    Split a PDF file into individual pages.
    
    Args:
        input_path (str): Path to the input PDF file
        output_folder (str): Directory to save individual pages
    """
    # Open the PDF document
    pdf_document = pymupdf.open(input_path)
    
    # Create output folder if it doesn't exist
    import os
    os.makedirs(output_folder, exist_ok=True)
    
    # Iterate through each page
    for page_num in range(len(pdf_document)):
        # Create a new PDF document for this page
        new_pdf = pymupdf.open()
        
        # Insert the current page into the new document
        new_pdf.insert_pdf(pdf_document, from_page=page_num, to_page=page_num)
        
        # Save the single-page PDF
        output_path = os.path.join(output_folder, f"page_{page_num + 1:03d}.pdf")
        new_pdf.save(output_path)
        new_pdf.close()
    
    # Close the original document
    pdf_document.close()
    print(f"Successfully split PDF into {len(pdf_document)} pages")
 
# Usage example
split_pdf_to_pages("input_document.pdf""output_pages")
 
cs

💡고급 PDF 분할 – 사용자 지정 파일명과 페이지 선택


출력 파일명을 더 세밀하게 지정하거나, 특정 페이지만 골라서 분할해야 할 때 유용한 확장 버전입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import pymupdf
import os
from pathlib import Path
 
def split_pdf_advanced(input_path, output_folder, 
                      name_prefix="page"
                      page_range=None
                      preserve_bookmarks=False):
    """
    Advanced PDF splitting with customizable options.
    
    Args:
        input_path (str): Path to the input PDF file
        output_folder (str): Directory to save individual pages
        name_prefix (str): Prefix for output filenames
        page_range (tuple): Optional (start, end) page range (1-indexed)
        preserve_bookmarks (bool): Whether to preserve bookmarks in output
    """
    pdf_document = pymupdf.open(input_path)
    
    # Create output directory
    Path(output_folder).mkdir(parents=True, exist_ok=True)
    
    # Determine page range
    total_pages = len(pdf_document)
    if page_range:
        start_page, end_page = page_range
        start_page = max(1, start_page) - 1  # Convert to 0-indexed
        end_page = min(total_pages, end_page)
    else:
        start_page, end_page = 0, total_pages
    
    pages_split = 0
    
    for page_num in range(start_page, end_page):
        # Create new PDF for this page
        new_pdf = pymupdf.open()
        
        # Insert the page
        new_pdf.insert_pdf(pdf_document, from_page=page_num, to_page=page_num)
        
        # Preserve bookmarks if requested
        if preserve_bookmarks:
            # Get bookmarks for this page
            bookmarks = pdf_document.get_toc()
            page_bookmarks = [bm for bm in bookmarks if bm[2== page_num + 1]
            if page_bookmarks:
                new_pdf.set_toc(page_bookmarks)
        
        # Generate output filename
        output_filename = f"{name_prefix}_{page_num + 1:03d}.pdf"
        output_path = os.path.join(output_folder, output_filename)
        
        # Save the page
        new_pdf.save(output_path)
        new_pdf.close()
        pages_split += 1
    
    pdf_document.close()
    print(f"Successfully split {pages_split} pages from {input_path}")
    return pages_split
 
# Usage examples
split_pdf_advanced("document.pdf""output", name_prefix="chapter")
split_pdf_advanced("document.pdf""output", page_range=(510))
cs

여러 개의 PDF를 한 번에 처리해야 한다면, 아래와 같이 배치(Batch) 분할 함수를 활용할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import pymupdf
import os
from pathlib import Path
import glob
 
def batch_split_pdfs(input_folder, output_base_folder):
    """
    Split multiple PDF files in a folder.
    
    Args:
        input_folder (str): Folder containing PDF files
        output_base_folder (str): Base folder for output
    """
    pdf_files = glob.glob(os.path.join(input_folder, "*.pdf"))
    
    if not pdf_files:
        print("No PDF files found in the input folder")
        return
    
    for pdf_file in pdf_files:
        # Create output folder for this PDF
        pdf_name = Path(pdf_file).stem
        output_folder = os.path.join(output_base_folder, pdf_name)
        
        try:
            split_pdf_to_pages(pdf_file, output_folder)
            print(f"Processed: {pdf_file}")
        except Exception as e:
            print(f"Error processing {pdf_file}: {str(e)}")
 
# Usage
batch_split_pdfs("input_pdfs""split_output")
cs

파일 작업 시에는 항상 오류 처리와 유효성 검증을 포함하는 것이 좋습니다.
아래 예제는 PDF 분할 과정에 예외 처리입력 파일 검증을 추가한 버전입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import pymupdf
import os
from pathlib import Path
 
def split_pdf_safe(input_path, output_folder):
    """
    Split PDF with comprehensive error handling.
    """
    try:
        # Validate input file
        if not os.path.exists(input_path):
            raise FileNotFoundError(f"Input file not found: {input_path}")
        
        if not input_path.lower().endswith('.pdf'):
            raise ValueError("Input file must be a PDF")
        
        # Open and validate PDF
        pdf_document = pymupdf.open(input_path)
        
        if pdf_document.is_encrypted:
            raise ValueError("Encrypted PDFs are not supported")
        
        if len(pdf_document) == 0:
            raise ValueError("PDF contains no pages")
        
        # Create output directory
        Path(output_folder).mkdir(parents=True, exist_ok=True)
        
        # Split pages
        for page_num in range(len(pdf_document)):
            new_pdf = pymupdf.open()
            new_pdf.insert_pdf(pdf_document, from_page=page_num, to_page=page_num)
            
            output_path = os.path.join(output_folder, f"page_{page_num + 1:03d}.pdf")
            new_pdf.save(output_path)
            new_pdf.close()
        
        pdf_document.close()
        return True, f"Successfully split {len(pdf_document)} pages"
        
    except Exception as e:
        return False, f"Error: {str(e)}"
 
# Usage with error handling
success, message = split_pdf_safe("input.pdf""output")
print(message)
cs

 

 

성능을 고려해야 하는 상황이라면, 특히 대용량 PDF다수의 파일을 처리할 때 아래 최적화 팁을 참고하세요.


💡성능 최적화 팁

  1. 메모리 관리
    작업이 끝난 PDF 문서는 즉시 close()로 닫아 메모리를 확보하세요.
  2. 배치 처리
    수천 페이지 이상의 대용량 파일은 페이지를 여러 번에 나눠서 처리하는 것이 안정적입니다.
  3. 빠른 디스크 사용
    파일 입출력이 많은 경우 SSD 사용이 HDD보다 훨씬 빠릅니다.
  4. 스레딩(Threading)
    여러 개의 작은 PDF를 한꺼번에 처리할 때는 I/O 중심의 작업이므로 스레딩을 활용하면 성능 향상에 도움이 됩니다.

💡PDF를 이미지로 변환 (대안 방식)

PDF 페이지를 개별 이미지로 변환하면, PDF가 아닌 환경에서도 페이지를 쉽게 표시하거나 공유할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import pymupdf
 
def split_pdf_to_images(input_path, output_folder, image_format="PNG", dpi=150):
    """
    Convert PDF pages to image files.
    
    Args:
        input_path (str): Path to input PDF
        output_folder (str): Output directory
        image_format (str): Image format (PNG, JPEG, etc.)
        dpi (int): Resolution for images
    """
    pdf_document = pymupdf.open(input_path)
    
    os.makedirs(output_folder, exist_ok=True)
    
    for page_num in range(len(pdf_document)):
        page = pdf_document[page_num]
        
        # Create transformation matrix for desired DPI
        mat = pymupdf.Matrix(dpi/72, dpi/72)
        
        # Render page to image
        pix = page.get_pixmap(matrix=mat)
        
        # Save image
        output_path = os.path.join(output_folder, f"page_{page_num + 1:03d}.{image_format.lower()}")
        pix.save(output_path)
    
    pdf_document.close()
    print(f"Converted {len(pdf_document)} pages to {image_format} images")
cs

PyMuPDF Pro는 PDF를 페이지 단위로 분리하는 작업을 간단하고 빠르게 처리할 수 있는 강력한 도구인데요,
기본적인 분할부터 파일명 지정, 여러 파일의 일괄 처리까지 유연하게 지원해 소규모 스크립트는 물론 대규모 문서 처리에도 잘 어울리고 속도와 안정성이 뛰어나서 대용량 문서나 반복 작업에도 부담이 적습니다.

작업 시에는 오류 처리를 꼼꼼히 하고, 사용이 끝난 문서는 반드시 close()로 닫아 성능과 메모리를 효율적으로 관리하는 것이 좋습니다. 소개드린 예제와 방법들을 활용하면, 상황에 맞는 PDF 분할 기능을 손쉽게 구현할 수 있습니다.

많은 도움이 되셨길 바라며 제품에 대해 더 궁금하신 내용이 있다면 아래의 홈페이지로 문의해주세요!
> 문의하기

 

이파피루스

ePapyrus는 항상 도움이 되겠습니다.이파피루스의 역사는 항상 고객, 파트너와의 삼위일체 속에서 성장하고 있습니다. 제품에 관련하여 궁금한 점이나 도움이 필요하시다면 언제든 연락바랍니다.

epapyrus.com