티스토리 뷰

📌 PyMuPDF Pro로 PDF 병합하기: 기본부터 고급 기능까지

PDF 병합은 보고서 통합, 연구 자료 합본, 문서 묶음 제작 등 다양한 작업에서 자주 필요한 기능입니다. PyMuPDF Pro는 빠르고 가벼우면서도 세밀한 제어가 가능해, 간단한 결합부터 페이지 범위 지정, 메타데이터 추가까지 모두 처리할 수 있습니다.

이 가이드에서는 PyMuPDF Pro로 PDF를 병합하는 방법을 다룹니다.

  • 기본 병합 (Concatenation)
  • 페이지 범위를 지정한 병합
  • 북마크와 메타데이터 유지 등 고급 병합

1. 기본 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 merge_pdfs(pdf_list, output_path):
    """
    Merge multiple PDFs into a single document
    
    Args:
        pdf_list: List of PDF file paths to merge
        output_path: Path for the output merged PDF
    """
    # Create a new PDF document
    merged_pdf = pymupdf.open()
    
    # Iterate through each PDF file
    for pdf_path in pdf_list:
        # Open the PDF
        pdf_document = pymupdf.open(pdf_path)
        
        # Insert all pages from the current PDF
        merged_pdf.insert_pdf(pdf_document)
        
        # Close the current PDF
        pdf_document.close()
    
    # Save the merged PDF
    merged_pdf.save(output_path)
    merged_pdf.close()
 
# Example usage
pdf_files = ['document1.pdf''document2.pdf''document3.pdf']
merge_pdfs(pdf_files, 'merged_document.pdf')
cs

2. 특정 페이지 범위 병합하기

전체 문서가 아니라 일부 페이지만 병합할 수도 있습니다.

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
import pymupdf
 
def merge_pdf_pages(pdf_info, output_path):
    """
    Merge specific pages from multiple PDFs
 
    Args:
        pdf_info: List of tuples (pdf_path, start_page, end_page)
        output_path: Path for the output merged PDF
    """
    merged_pdf = pymupdf.open()
 
    for pdf_path, start_page, end_page in pdf_info:
        pdf_document = pymupdf.open(pdf_path)
 
        # Insert specific page range (0-indexed)
        merged_pdf.insert_pdf(
            pdf_document,
            from_page=start_page,
            to_page=end_page
        )
 
        pdf_document.close()
 
    merged_pdf.save(output_path)
    merged_pdf.close()
 
# Example:
page_ranges = [
    ('document1.pdf'01),  # First 2 pages
    ('document2.pdf'36)  # Pages 4-7
]
merge_pdf_pages(page_ranges, 'custom_merged.pdf')
cs

3. 오류 처리 포함 고급 병합

실제 환경에서는 오류 처리와 유효성 검사가 중요합니다.

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import pymupdf
import os
 
from pathlib import Path
 
def merge_pdfs_robust(pdf_list, output_path, include_bookmarks=True):
    """
    Robustly merge PDFs with error handling and optional bookmark preservation
 
    Args:
        pdf_list: List of PDF file paths to merge
        output_path: Path for the output merged PDF
        include_bookmarks: Whether to preserve bookmarks from source PDFs
    """
    merged_pdf = pymupdf.open()
 
    try:
        for i, pdf_path in enumerate(pdf_list):
            # Check if file exists
            if not os.path.exists(pdf_path):
                print(f"Warning: File {pdf_path} not found, skipping...")
                continue
 
            try:
                pdf_document = pymupdf.open(pdf_path)
 
                # Check if PDF is valid and has pages
                if pdf_document.page_count == 0:
                    print(f"Warning: {pdf_path} has no pages, skipping...")
                    pdf_document.close()
                    continue
 
                # Get current page count for bookmark offset
                current_page_count = merged_pdf.page_count
 
                # Insert all pages
                merged_pdf.insert_pdf(pdf_document)
 
                # Handle bookmarks if requested
                if include_bookmarks:
                    try:
                        toc = pdf_document.get_toc()
                        if toc:
                            # Adjust bookmark page numbers for merged document
                            adjusted_toc = []
                            for level, title, page in toc:
                                adjusted_toc.append([level, title, page + current_page_count])
 
                            # Get existing TOC and extend it
                            existing_toc = merged_pdf.get_toc()
                            existing_toc.extend(adjusted_toc)
                            merged_pdf.set_toc(existing_toc)
                    except:
                        print(f"Warning: Could not process bookmarks for {pdf_path}")
 
                pdf_document.close()
                print(f"Successfully merged: {pdf_path}")
 
            except Exception as e:
                print(f"Error processing {pdf_path}: {str(e)}")
                continue
 
        # Save the merged PDF
        if merged_pdf.page_count > 0:
            merged_pdf.save(output_path)
            print(f"Merged PDF saved to: {output_path}")
            print(f"Total pages: {merged_pdf.page_count}")
        else:
            print("No pages to merge!")
 
    except Exception as e:
        print(f"Error during merge process: {str(e)}")
 
    finally:
        merged_pdf.close()
 
# Example usage
pdf_files = ['report1.pdf''report2.pdf''appendix.pdf']
merge_pdfs_robust(pdf_files, 'final_report.pdf')
cs

4. 원하는 위치에 페이지 삽입

병합 시 페이지를 원하는 위치에 끼워 넣을 수도 있습니다.

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 merge_with_custom_insertion(base_pdf, insertions, output_path):
    """
    Merge PDFs with custom insertion points
 
    Args:
        base_pdf: Path to the base PDF document
        insertions: List of tuples (pdf_path, insert_after_page)
        output_path: Path for the output merged PDF
    """
    # Open the base document
    merged_pdf = pymupdf.open(base_pdf)
 
    # Sort insertions by page number (descending) to avoid page number shifts
    insertions.sort(key=lambda x: x[1], reverse=True)
 
    for pdf_path, insert_at_page in insertions:
        insert_pdf = pymupdf.open(pdf_path)
 
        # Insert at specified page
        merged_pdf.insert_pdf(
            insert_pdf,
            start_at=insert_at_page
        )
 
        insert_pdf.close()
 
    merged_pdf.save(output_path)
    merged_pdf.close()
 
# Example: Insert cover.pdf at page 1, insert appendix.pdf at page 9
insertions = [
    ('cover.pdf'0),
    ('appendix.pdf'8)
]
merge_with_custom_insertion('main_document.pdf', insertions, 'complete_document.pdf')
cs

5. 대용량 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 merge_large_pdfs(pdf_list, output_path, chunk_size=10):
    """
    Merge large PDFs with memory optimization
 
    Args:
        pdf_list: List of PDF file paths to merge
        output_path: Path for the output merged PDF
        chunk_size: Number of pages to process at once
    """
    merged_pdf = pymupdf.open()
 
    for pdf_path in pdf_list:
        pdf_document = pymupdf.open(pdf_path)
        total_pages = pdf_document.page_count
 
        # Process in chunks to manage memory
        for start_page in range(0, total_pages, chunk_size):
            end_page = min(start_page + chunk_size - 1, total_pages - 1)
 
            # Create temporary document for this chunk
            temp_doc = pymupdf.open()
            temp_doc.insert_pdf(pdf_document, from_page=start_page, to_page=end_page)
 
            # Insert chunk into merged document
            merged_pdf.insert_pdf(temp_doc)
 
            # Clean up temporary document
            temp_doc.close()
 
        pdf_document.close()
 
    merged_pdf.save(output_path)
    merged_pdf.close()
 
merge_large_pdfs(["large-doc-1","large-doc-2.pdf"], "output.pdf")
cs

6. 병합된 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
38
39
40
41
42
43
44
45
46
47
import pymupdf
 
def merge_with_metadata(pdf_list, output_path, metadata=None):
    """
    Merge PDFs and add custom metadata
 
    Args:
        pdf_list: List of PDF file paths to merge
        output_path: Path for the output merged PDF
        metadata: Dictionary of metadata to add
    """
    merged_pdf = pymupdf.open()
 
    # Merge the PDFs
    for pdf_path in pdf_list:
        pdf_document = pymupdf.open(pdf_path)
        merged_pdf.insert_pdf(pdf_document)
        pdf_document.close()
 
    # Add metadata
    if metadata:
        merged_pdf.set_metadata(metadata)
    else:
        # Default metadata
        default_metadata = {
            'title''Merged PDF Document',
            'author''PyMuPDF Merger',
            'subject''Combined PDF files',
            'creator''Python PyMuPDF',
            'producer''PyMuPDF Library'
        }
        merged_pdf.set_metadata(default_metadata)
 
    merged_pdf.save(output_path)
    merged_pdf.close()
 
# Example with custom metadata
custom_metadata = {
    'title''Annual Report 2024',
    'author''Your Company',
    'subject''Financial and operational results',
    'keywords''annual report, financial, operations'
}
 
merge_with_metadata(['q1.pdf''q2.pdf''q3.pdf''q4.pdf'],
                   'annual_report_2024.pdf',
                   custom_metadata)
cs

💡프랙티스 & 팁

1. 문서 닫기
PyMuPDF Pro문서는 작업이 끝나면 반드시 닫아 메모리를 해제하세요.

2. 암호화된 PDF 처리
PDF가 암호화되어 있는지 확인하고, 필요하면 인증을 진행하세요.

if pdf_document.needs_pass:
    pdf_document.authenticate("password")

3. 입력 파일 검증
처리 전, 파일이 존재하고 유효한 PDF인지 확인하세요.

4. 메모리 관리
대용량 문서는 청크 단위 처리나 임시 파일 사용을 고려하세요.

5.문서 구조 유지
관련 문서를 병합할 때는 북마크 등 기존 구조를 보존하세요.


PyMuPDF Pro는 기본 병합부터 페이지 범위 지정, 메타데이터 관리, 성능 최적화까지 폭넓은 기능을 제공합니다. 이 가이드의 예제를 바탕으로, 단순한 스크립트부터 대규모 문서 처리 자동화까지 다양한 병합 작업을 구현할 수 있습니다.

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