티스토리 뷰

PyMuPDF Pro로 PDF를 이미지로 변환하기: 완벽 가이드
PDF는 어디서나 쓰이지만, 프레젠테이션이나 웹에 올리거나 추가 가공을 위해 이미지로 변환해야 할 때가 있습니다.
PyMuPDF Pro는 이 과정을 빠르고 효율적으로 처리할 수 있는 파워풀한 파이썬 라이브러리입니다.
PyMuPDF Pro란?
PyMuPDF Pro는 MuPDF의 파이썬 바인딩으로, 가볍고 빠르며 메모리 효율성이 뛰어난 PDF/XPS 처리 도구입니다.
폰트, 이미지, 벡터 그래픽이 복잡하게 섞인 PDF도 고품질로 다룰 수 있다는 점이 강점입니다.
설치 방법
설치는 간단합니다. pip으로 바로 설치할 수 있습니다.
pip install PyMuPDF
추가적인 이미지 형식을 다루려면 Pillow 라이브러리 설치도 권장됩니다.
pip install PyMuPDF Pillow
기본 변환: 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
|
import pymupdf
def pdf_to_image_basic(pdf_path, output_path, page_num=0):
"""
Convert a single PDF page to an image
Args:
pdf_path: Path to the PDF file
output_path: Path for the output image
page_num: Page number to convert (0-indexed)
"""
# Open the PDF
doc = pymupdf.open(pdf_path)
# Get the specified page
page = doc[page_num]
# Render page to a pixmap (image)
pix = page.get_pixmap()
# Save the image
pix.save(output_path)
# Clean up
doc.close()
# Usage example
pdf_to_image_basic("document.pdf", "page_0.png")
Copy
|
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
|
import pymupdf
import os
def pdf_to_images_all_pages(pdf_path, output_dir, image_format="png"):
"""
Convert all pages of a PDF to individual images
Args:
pdf_path: Path to the PDF file
output_dir: Directory to save images
image_format: Output format (png, jpg, etc.)
"""
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Open the PDF
doc = pymupdf.open(pdf_path)
# Get the base filename without extension
base_name = os.path.splitext(os.path.basename(pdf_path))[0]
for page_num in range(doc.page_count):
# Get the page
page = doc[page_num]
# Render to pixmap
pix = page.get_pixmap()
# Create output filename
output_path = os.path.join(
output_dir,
f"{base_name}_page_{page_num + 1}.{image_format}"
)
# Save the image
pix.save(output_path)
print(f"Saved: {output_path}")
doc.close()
print(f"Converted {doc.page_count} pages successfully!")
# Usage example
pdf_to_images_all_pages("report.pdf", "output_images", "png")
|
cs |
고해상도 변환
해상도를 높이고 싶다면 변환 시 확대 비율(zoom factor)을 지정할 수 있습니다.
|
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
|
import pymupdf
def pdf_to_image_high_res(pdf_path, output_path, page_num=0, zoom_factor=2.0):
"""
Convert PDF page to high-resolution image
Args:
pdf_path: Path to the PDF file
output_path: Path for the output image
page_num: Page number to convert
zoom_factor: Resolution multiplier (2.0 = double resolution)
"""
doc = pymupdf.open(pdf_path)
page = doc[page_num]
# Create transformation matrix for higher resolution
mat = pymupdf.Matrix(zoom_factor, zoom_factor)
# Render with the transformation matrix
pix = page.get_pixmap(matrix=mat)
pix.save(output_path)
doc.close()
# Create a high-resolution image
pdf_to_image_high_res("document.pdf", "high_res_page.png", zoom_factor=4.0)
|
cs |
다양한 이미지 포맷 지원
PyMuPDF는 여러 가지 이미지 포맷을 지원합니다.
예를 들어 PNG로 변환할 때는 알파 채널(투명도)을 유지할 수도 있습니다.
아래는 포맷별 요구사항을 처리하는 방법입니다:
|
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
|
import pymupdf
def pdf_to_image_format_options(pdf_path, output_path, page_num=0,
format_type="png", quality=95):
"""
Convert PDF to image with format-specific options
Args:
pdf_path: Path to the PDF file
output_path: Path for the output image
page_num: Page number to convert
format_type: Image format (png, jpg, ppm, etc.)
quality: JPEG quality (1-100, only for JPEG)
"""
doc = pymupdf.open(pdf_path)
page = doc[page_num]
if format_type.lower() == "jpg" or format_type.lower() == "jpeg":
# For JPEG, we can specify quality
pix = page.get_pixmap()
pix.save(output_path, jpg_quality=quality)
elif format_type.lower() == "png":
# PNG supports transparency
pix = page.get_pixmap(alpha=True) # Include alpha channel
pix.save(output_path)
else:
# Default handling for other formats
pix = page.get_pixmap()
pix.save(output_path)
doc.close()
# Examples
pdf_to_image_format_options("document.pdf", "output.jpg", format_type="jpg", quality=85)
pdf_to_image_format_options("document.pdf", "output.png", format_type="png")
|
cs |
여러 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
48
49
50
51
52
53
54
55
56
57
58
59
|
import pymupdf
import os
from pathlib import Path
def batch_pdf_to_images(input_dir, output_dir, image_format="png", zoom_factor=1.0):
"""
Convert all PDFs in a directory to images
Args:
input_dir: Directory containing PDF files
output_dir: Directory to save images
image_format: Output image format
zoom_factor: Resolution multiplier
"""
input_path = Path(input_dir)
output_path = Path(output_dir)
# Create output directory
output_path.mkdir(parents=True, exist_ok=True)
# Find all PDF files
pdf_files = list(input_path.glob("*.pdf"))
if not pdf_files:
print("No PDF files found in the input directory.")
return
print(f"Found {len(pdf_files)} PDF files to process...")
for pdf_file in pdf_files:
try:
doc = pymupdf.open(pdf_file)
pdf_name = pdf_file.stem
# Create subdirectory for this PDF's images
pdf_output_dir = output_path / pdf_name
pdf_output_dir.mkdir(exist_ok=True)
# Convert each page
for page_num in range(doc.page_count):
page = doc[page_num]
if zoom_factor != 1.0:
mat = pymupdf.Matrix(zoom_factor, zoom_factor)
pix = page.get_pixmap(matrix=mat)
else:
pix = page.get_pixmap()
output_file = pdf_output_dir / f"page_{page_num + 1}.{image_format}"
pix.save(str(output_file))
doc.close()
print(f"✓ Processed {pdf_file.name}: {doc.page_count} pages")
except Exception as e:
print(f"✗ Error processing {pdf_file.name}: {str(e)}")
# Usage
batch_pdf_to_images("input_pdfs", "output_images", "png", 2.0)
|
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
import pymupdf
import os
from pathlib import Path
def convert_pdf_to_images_robust(pdf_path, output_dir=None,
image_format="png", zoom_factor=1.0,
page_range=None):
"""
Robust PDF to image conversion with error handling
Args:
pdf_path: Path to PDF file
output_dir: Output directory (defaults to PDF directory)
image_format: Output format
zoom_factor: Resolution multiplier
page_range: Tuple (start, end) for page range, or None for all pages
Returns:
List of successfully created image paths
"""
try:
# Validate input file
if not os.path.exists(pdf_path):
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
# Set up output directory
if output_dir is None:
output_dir = os.path.dirname(pdf_path)
os.makedirs(output_dir, exist_ok=True)
# Open PDF
doc = pymupdf.open(pdf_path)
# Determine page range
total_pages = doc.page_count
if page_range:
start_page, end_page = page_range
start_page = max(0, start_page)
end_page = min(total_pages, end_page)
else:
start_page, end_page = 0, total_pages
# Convert pages
created_files = []
base_name = Path(pdf_path).stem
for page_num in range(start_page, end_page):
try:
page = doc[page_num]
# Apply zoom if specified
if zoom_factor != 1.0:
mat = pymupdf.Matrix(zoom_factor, zoom_factor)
pix = page.get_pixmap(matrix=mat)
else:
pix = page.get_pixmap()
# Create output filename
output_file = os.path.join(
output_dir,
f"{base_name}_page_{page_num + 1}.{image_format}"
)
# Save image
pix.save(output_file)
created_files.append(output_file)
print(f"✓ Page {page_num + 1}/{total_pages} converted")
except Exception as e:
print(f"✗ Error converting page {page_num + 1}: {str(e)}")
continue
doc.close()
return created_files
except Exception as e:
print(f"Error processing PDF: {str(e)}")
return []
# Usage examples
images = convert_pdf_to_images_robust("document.pdf")
print(f"Created {len(images)} images")
# Convert only pages 1-5 with high resolution
images = convert_pdf_to_images_robust(
"large_document.pdf",
"output_images",
"jpg",
zoom_factor=2.0,
page_range=(0, 5)
)
|
cs |
성능 최적화 팁
- 메모리 관리: 대용량 PDF는 한 번에 불러들이지 말고 페이지 단위로 처리하는 것이 안전합니다.
- 포맷 선택: 사진 위주의 문서는 JPEG, 텍스트와 선명한 그래픽이 많은 문서는 PNG가 적합합니다.
- 해상도 조정: 배율을 높이면 품질은 좋아지지만 파일 크기도 커집니다. 테스트를 통해 적절한 균형을 찾으세요.
- 배치 처리: 여러 파일을 변환할 때는 문서 객체를 재사용하면 속도와 효율이 올라갑니다.
결론
PyMuPDF Pro는 PDF를 이미지로 변환할 때 가볍고 빠르면서도 강력한 도구입니다.
한두 페이지를 변환하든, 수백 개의 문서를 일괄 처리하든 필요한 기능을 충분히 제공합니다.
이 가이드에서 다룬 방법들은 프로젝트에 바로 적용할 수 있는 실용적인 기반이 될 것입니다.
특히 대용량 문서를 다룰 때는 메모리 관리에 신경 쓰고, 변환 과정에서 발생할 수 있는 오류를 안정적으로 처리하는 것이 중요합니다.
빠른 성능과 높은 안정성을 갖춘 PyMuPDF Pro는 단순한 스크립트 작업부터 실무용 애플리케이션까지 폭넓게 활용할 수 있습니다.
많은 도움이 되셨길 바라며 제품에 대해 더 궁금하신 내용이 있다면 아래의 홈페이지로 문의해주세요!
> 문의하기
'PyMuPDF Pro' 카테고리의 다른 글
| PyMuPDF Pro 설치 가이드 (0) | 2025.11.11 |
|---|---|
| PyMuPDF Pro로 PDF에서 텍스트 검색·치환하기: 샘플 코드 포함 (0) | 2025.08.22 |
| 'PyMuPDF Pro'로 PDF 병합하기! 완벽 가이드 (샘플 코드 포함) (2) | 2025.08.12 |
| PDF를 페이지별로 분할하는 가장 쉬운 방법: 'PyMuPDF Pro' (샘플 코드 포함) (5) | 2025.08.11 |
| 'PyMuPDF Pro'를 활용한 PDF 주석 및 강조 표시: 샘플 코드 포함 (5) | 2025.08.08 |
- Total
- Today
- Yesterday
- 전자서식
- 전자문서
- 아티펙스
- 이파피루스
- PDF-Pro
- 파이썬라이브러리
- 이벤트
- PyMuPDFPro
- epapyrus
- pdf추출
- 문서ai
- 고장예측
- 인공지능
- ocr
- 피터펜
- pdf뷰어
- PDF변환
- djvu
- 피터팬
- paperless
- PDF편집
- pdf프로
- 모터센스
- PDFpro
- 페이퍼리스
- pdf프로그램
- 예지보전
- Ai
- 스마트공장
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |