Skip to content

Instantly share code, notes, and snippets.

@dcbark01
Created December 10, 2021 16:16
Show Gist options
  • Save dcbark01/56045580754ab6c27445b77a83290284 to your computer and use it in GitHub Desktop.
Save dcbark01/56045580754ab6c27445b77a83290284 to your computer and use it in GitHub Desktop.
Create an image from a PDF file
from pdf2image import convert_from_path
from PyPDF2 import PdfFileReader
def pdf_to_image(file: str, page_num=0, output_file=None) -> Image:
""" Convert a PDF to a PIL Image. """
pdf_page = PdfFileReader(open(file, 'rb')).getPage(page_num)
pdf_shape = pdf_page.mediaBox
pdf_height = pdf_shape[3] - pdf_shape[1]
pdf_width = pdf_shape[2] - pdf_shape[0]
converted_images = convert_from_path(file, size=(pdf_width, pdf_height))
img = converted_images[0]
if output_file:
img.save(output_file)
return img
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment