feat(pdf-to-jpg): convert pdf pages to resized jpgs
This commit is contained in:
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env -S uv run --script
|
||||
# /// script
|
||||
# dependencies = ["pdf2image", "Pillow"]
|
||||
# ///
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import pdf2image
|
||||
from PIL import Image
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Convert PDF pages to JPG images.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("pdf_path", type=Path, help="Path to the PDF file.")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def save_images(images: list[Image.Image], save_dir: Path, base_name: str) -> None:
|
||||
for i, img in enumerate(images, start=1):
|
||||
width, height = img.size
|
||||
if width > 2000:
|
||||
ratio = 2000 / width
|
||||
new_size = (2000, int(height * ratio))
|
||||
img = img.resize(new_size, resample=Image.LANCZOS)
|
||||
out_path = save_dir / f"{base_name}-{i:03d}.jpg"
|
||||
img.save(out_path, format="JPEG")
|
||||
logging.info(f"Saved {out_path}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
pdf_path: Path = args.pdf_path
|
||||
if not pdf_path.exists():
|
||||
logging.error(f"File not found: {pdf_path}")
|
||||
return
|
||||
try:
|
||||
images = pdf2image.convert_from_path(pdf_path=str(pdf_path))
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to convert PDF: {e}")
|
||||
return
|
||||
save_images(
|
||||
images=images,
|
||||
save_dir=pdf_path.parent,
|
||||
base_name=pdf_path.stem,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user