Skip to content

Instantly share code, notes, and snippets.

@aaronvg
Created October 7, 2024 15:26
Show Gist options
  • Select an option

  • Save aaronvg/71b1fe7287ee81a8034028d436d22986 to your computer and use it in GitHub Desktop.

Select an option

Save aaronvg/71b1fe7287ee81a8034028d436d22986 to your computer and use it in GitHub Desktop.
thing
import os
import fire
from pdf2image import convert_from_bytes
from PIL import Image
import io
def convert_pdf_to_image(pdf_path: str, output_path: str, page: int = 1, dpi: int = 200):
try:
# Read PDF file
with open(pdf_path, 'rb') as file:
pdf_bytes = file.read()
# Convert PDF to image
images = convert_from_bytes(pdf_bytes, dpi=dpi)
# Check if the specified page number is valid
if 1 <= page <= len(images):
image = images[page - 1] # Adjust for 0-based indexing
# Ensure the output directory exists
os.makedirs(os.path.dirname(output_path), exist_ok=True)
# Save the image
image.save(output_path, 'PNG')
print(f"Image saved successfully at {output_path}")
else:
print(f"Invalid page number. The PDF has {len(images)} pages.")
except Exception as e:
print(f"Error converting PDF to image: {str(e)}")
if __name__ == "__main__":
fire.Fire(convert_pdf_to_image)
# Example usage from command line:
# python script.py path/to/your/input.pdf path/to/output/image.png --page 2 --dpi 200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment