convert_pdf_to_images.py 1008 B

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