Created
December 10, 2021 16:16
-
-
Save dcbark01/56045580754ab6c27445b77a83290284 to your computer and use it in GitHub Desktop.
Create an image from a PDF file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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