stzhao commited on
Commit
b3def2c
·
verified ·
1 Parent(s): 12aeac2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py CHANGED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import fitz # PyMuPDF
3
+ from PIL import Image
4
+ import os
5
+
6
+ def pdf_to_png(pdf_file, dpi=300):
7
+ # Open the PDF file
8
+ pdf_document = fitz.open(stream=pdf_file.read(), filetype="pdf")
9
+
10
+ # Create a temporary directory to store the PNG files
11
+ output_folder = "temp_output_images"
12
+ if not os.path.exists(output_folder):
13
+ os.makedirs(output_folder)
14
+
15
+ # List to store the paths of the generated PNG files
16
+ png_files = []
17
+
18
+ # Iterate through each page in the PDF
19
+ for page_num in range(len(pdf_document)):
20
+ # Get the page
21
+ page = pdf_document.load_page(page_num)
22
+
23
+ # Render the page to a Pixmap with the specified DPI
24
+ pix = page.get_pixmap(matrix=fitz.Matrix(dpi/72, dpi/72))
25
+
26
+ # Convert the Pixmap to a PIL Image
27
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
28
+
29
+ # Save the image as a PNG file
30
+ output_path = os.path.join(output_folder, f"page_{page_num + 1}.png")
31
+ img.save(output_path, "PNG")
32
+
33
+ png_files.append(output_path)
34
+
35
+ return png_files
36
+
37
+ # Define the Gradio interface
38
+ iface = gr.Interface(
39
+ fn=pdf_to_png,
40
+ inputs=[
41
+ gr.File(label="Upload PDF file"),
42
+ gr.Slider(minimum=72, maximum=600, value=300, step=1, label="DPI")
43
+ ],
44
+ outputs=[gr.Gallery(label="Converted PNG Images")],
45
+ title="PDF to PNG Converter",
46
+ description="Upload a PDF file and convert each page to a PNG image."
47
+ )
48
+
49
+ # Launch the Gradio interface
50
+ iface.launch()