Last active
September 22, 2021 22:34
-
-
Save moosetraveller/95d20cd636d0097c4a89f0fe38d0969e to your computer and use it in GitHub Desktop.
Convert a PDF File to Images
This file contains 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
""" | |
Converts PDF pages to images. | |
```python | |
pip install PyMuPDF | |
pip install PySimpleGUI | |
``` | |
:See also: | |
https://pymupdf.readthedocs.io/en/latest/faq.html | |
https://towardsdatascience.com/convert-pdf-to-image-in-python-using-pymupdf-9cc8f602525b | |
:Authors: | |
Thomas Zuberbuehler | |
""" | |
import os | |
import glob | |
import sys | |
import fitz | |
import PySimpleGUI as sg | |
layout = [ | |
[ | |
sg.Text("Input PDF File"), | |
sg.InputText(key="filepath", readonly=True), | |
sg.FileBrowse(key="selector", file_types=(("PDF Files", "*.pdf"),)) | |
], | |
[sg.Button("Convert", key="convert")], | |
] | |
def convert_pdf(filepath): | |
if not filepath or not os.path.isfile(filepath): | |
return | |
filename = os.path.basename(filepath) | |
folder = os.path.dirname(filepath) | |
zoom_x = 3.0 | |
zoom_y = 3.0 | |
mat = fitz.Matrix(zoom_x, zoom_y) | |
doc = fitz.open(filepath) | |
for page in doc: | |
pix = page.get_pixmap(matrix=mat) | |
pix.save(os.path.join(folder, filename.replace(".pdf", f"{page.number}.png"))) | |
sg.Popup("PDF File successfully converted to PNG Images.", title="Done") | |
window = sg.Window("Flatten PDF pages", layout) | |
while True: | |
event, values = window.read() | |
if event == sg.WIN_CLOSED or event == 'Cancel': | |
break | |
if event == "selector": | |
window["filepath"].update(values.get("selector", "")) | |
if event == "convert": | |
convert_pdf(values.get("filepath", None)) | |
window.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment