File size: 1,521 Bytes
b3def2c
 
 
 
 
 
 
ed6d2dd
b3def2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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()