DocRes-Appearance / examples /check_pdf_dimensions.py
Seth Thompson
add pdf cli
5dc8e48
Raw History Blame Contribute Delete
1.84 kB
#!/usr/bin/env python3
"""
Compute a DPI to keep rendered images within a max page size in inches.
"""
import argparse
import sys
from pathlib import Path
from pypdf import PdfReader
POINTS_PER_INCH = 72.0
def main() -> int:
parser = argparse.ArgumentParser(
description="Check PDF page dimensions against a max size in inches."
)
parser.add_argument("pdf_path", type=str, help="Path to the PDF file.")
parser.add_argument(
"--max-inches",
type=float,
default=12.0,
help="Maximum allowed width or height in inches (default: 12).",
)
parser.add_argument(
"--default-dpi",
type=int,
default=200,
help="Default DPI when within limits (default: 200).",
)
args = parser.parse_args()
pdf_path = Path(args.pdf_path)
if not pdf_path.exists():
print(f"Error: PDF file not found: {pdf_path}", file=sys.stderr)
return 1
reader = PdfReader(str(pdf_path))
max_width_in = 0.0
max_height_in = 0.0
for page in reader.pages:
width_in = float(page.mediabox.width) / POINTS_PER_INCH
height_in = float(page.mediabox.height) / POINTS_PER_INCH
max_width_in = max(max_width_in, width_in)
max_height_in = max(max_height_in, height_in)
max_dim_in = max(max_width_in, max_height_in)
dpi = args.default_dpi
if max_dim_in > args.max_inches:
scale = args.max_inches / max_dim_in
dpi = max(1, int(args.default_dpi * scale))
print(
"Warning: PDF page size exceeds "
f"{args.max_inches:g} inches: "
f"{max_width_in:.2f}in x {max_height_in:.2f}in; "
f"reducing DPI to {dpi}.",
file=sys.stderr,
)
print(dpi)
return 0
if __name__ == "__main__":
raise SystemExit(main())