-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf_to_png.py
More file actions
77 lines (59 loc) · 2.09 KB
/
Copy pathpdf_to_png.py
File metadata and controls
77 lines (59 loc) · 2.09 KB
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
from __future__ import annotations
import argparse
from pathlib import Path
try:
import fitz
except ImportError as exc:
raise SystemExit(
"PyMuPDF is required. Install it with: pip install PyMuPDF"
) from exc
def convert_pdf_to_png(pdf_path: Path, output_dir: Path, dpi: int = 200) -> list[Path]:
"""Convert each page of a PDF file into a PNG image."""
if not pdf_path.exists():
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
output_dir.mkdir(parents=True, exist_ok=True)
created_files: list[Path] = []
zoom = dpi / 72
matrix = fitz.Matrix(zoom, zoom)
with fitz.open(pdf_path) as document:
pdf_stem = pdf_path.stem
for page_index in range(document.page_count):
page = document.load_page(page_index)
pixmap = page.get_pixmap(matrix=matrix, alpha=False)
output_path = output_dir / f"{pdf_stem}_page_{page_index + 1}.png"
pixmap.save(output_path)
created_files.append(output_path)
return created_files
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Convert every page of a PDF file into PNG images."
)
parser.add_argument("pdf", type=Path, help="Path to the input PDF file")
parser.add_argument(
"-o",
"--output-dir",
type=Path,
help="Directory where PNG files will be written. Defaults to <pdf_name>_pages",
)
parser.add_argument(
"--dpi",
type=int,
default=200,
help="Rendering DPI for output images (default: 200)",
)
return parser
def main() -> None:
parser = build_parser()
args = parser.parse_args()
pdf_path = args.pdf.resolve()
output_dir = (
args.output_dir.resolve()
if args.output_dir
else pdf_path.with_name(f"{pdf_path.stem}_pages")
)
created_files = convert_pdf_to_png(pdf_path, output_dir, dpi=args.dpi)
print(f"Converted {len(created_files)} page(s) to PNG:")
for file_path in created_files:
print(file_path)
if __name__ == "__main__":
main()