Spaces:
Sleeping
Sleeping
import gradio as gr | |
import fitz # PyMuPDF | |
from PIL import Image | |
import os | |
def pdf_to_png(pdf_file, dpi=300): | |
# Open the PDF file | |
pdf_document = fitz.open(pdf_file) | |
# Create a temporary directory to store the PNG files | |
output_folder = "temp_output_images" | |
if not os.path.exists(output_folder): | |
os.makedirs(output_folder) | |
# List to store the paths of the generated PNG files | |
png_files = [] | |
# Iterate through each page in the PDF | |
for page_num in range(len(pdf_document)): | |
# Get the page | |
page = pdf_document.load_page(page_num) | |
# Render the page to a Pixmap with the specified DPI | |
pix = page.get_pixmap(matrix=fitz.Matrix(dpi/72, dpi/72)) | |
# Convert the Pixmap to a PIL Image | |
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) | |
# Save the image as a PNG file | |
output_path = os.path.join(output_folder, f"page_{page_num + 1}.png") | |
img.save(output_path, "PNG") | |
png_files.append(output_path) | |
return png_files | |
# Define the Gradio interface | |
iface = gr.Interface( | |
fn=pdf_to_png, | |
inputs=[ | |
gr.File(label="Upload PDF file"), | |
gr.Slider(minimum=72, maximum=600, value=300, step=1, label="DPI") | |
], | |
outputs=[gr.Gallery(label="Converted PNG Images")], | |
title="PDF to PNG Converter", | |
description="Upload a PDF file and convert each page to a PNG image." | |
) | |
# Launch the Gradio interface | |
iface.launch() |