Branchwell

Skillfarm / skills · skillfarm.ai / converted / pdf / scripts / convert_pdf_to_images.py

1import os
2import sys
3
4from pdf2image import convert_from_path
5
6
7
8
9def convert(pdf_path, output_dir, max_dim=1000):
10 images = convert_from_path(pdf_path, dpi=200)
11
12 for i, image in enumerate(images):
13 width, height = image.size
14 if width > max_dim or height > max_dim:
15 scale_factor = min(max_dim / width, max_dim / height)
16 new_width = int(width * scale_factor)
17 new_height = int(height * scale_factor)
18 image = image.resize((new_width, new_height))
19
20 image_path = os.path.join(output_dir, f"page_{i+1}.png")
21 image.save(image_path)
22 print(f"Saved page {i+1} as {image_path} (size: {image.size})")
23
24 print(f"Converted {len(images)} pages to PNG images")
25
26
27if __name__ == "__main__":
28 if len(sys.argv) != 3:
29 print("Usage: convert_pdf_to_images.py [input pdf] [output directory]")
30 sys.exit(1)
31 pdf_path = sys.argv[1]
32 output_directory = sys.argv[2]
33 convert(pdf_path, output_directory)