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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import fitz # PyMuPDF
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import io
|
| 6 |
+
import tempfile
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
|
| 10 |
+
st.set_page_config(
|
| 11 |
+
page_title="PDF to Single Image Converter",
|
| 12 |
+
page_icon="๐",
|
| 13 |
+
layout="centered"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
st.title("๐ PDF to Single Image Converter")
|
| 17 |
+
st.write("Upload a PDF and convert it into a single image containing all pages.")
|
| 18 |
+
|
| 19 |
+
def pdf_to_single_image(pdf_path, output_format="PNG", dpi=300):
|
| 20 |
+
"""Convert all pages of a PDF to a single image file"""
|
| 21 |
+
# Open the PDF
|
| 22 |
+
pdf_document = fitz.open(pdf_path)
|
| 23 |
+
num_pages = len(pdf_document)
|
| 24 |
+
|
| 25 |
+
# Calculate total height and get width
|
| 26 |
+
total_height = 0
|
| 27 |
+
width = 0
|
| 28 |
+
|
| 29 |
+
# First pass to calculate dimensions
|
| 30 |
+
zooms = []
|
| 31 |
+
for page_num in range(num_pages):
|
| 32 |
+
page = pdf_document[page_num]
|
| 33 |
+
zoom = dpi / 72 # 72 is the default DPI for PDFs
|
| 34 |
+
zooms.append(zoom)
|
| 35 |
+
rect = page.rect
|
| 36 |
+
width = max(width, int(rect.width * zoom))
|
| 37 |
+
total_height += int(rect.height * zoom)
|
| 38 |
+
|
| 39 |
+
# Create a new image with the calculated dimensions
|
| 40 |
+
result_image = Image.new("RGB", (width, total_height), (255, 255, 255))
|
| 41 |
+
|
| 42 |
+
# Second pass to render pages
|
| 43 |
+
current_height = 0
|
| 44 |
+
progress_bar = st.progress(0)
|
| 45 |
+
status_text = st.empty()
|
| 46 |
+
|
| 47 |
+
for page_num in range(num_pages):
|
| 48 |
+
status_text.text(f"Processing page {page_num + 1}/{num_pages}")
|
| 49 |
+
page = pdf_document[page_num]
|
| 50 |
+
zoom = zooms[page_num]
|
| 51 |
+
|
| 52 |
+
# Get the page as a pixmap
|
| 53 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(zoom, zoom))
|
| 54 |
+
|
| 55 |
+
# Convert pixmap to PIL Image
|
| 56 |
+
page_image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 57 |
+
|
| 58 |
+
# Paste this page into the result image
|
| 59 |
+
result_image.paste(page_image, (0, current_height))
|
| 60 |
+
current_height += pix.height
|
| 61 |
+
|
| 62 |
+
# Update progress
|
| 63 |
+
progress_bar.progress((page_num + 1) / num_pages)
|
| 64 |
+
|
| 65 |
+
# Create a byte buffer for the image
|
| 66 |
+
buf = io.BytesIO()
|
| 67 |
+
if output_format.upper() == "PNG":
|
| 68 |
+
result_image.save(buf, format="PNG")
|
| 69 |
+
else:
|
| 70 |
+
result_image.save(buf, format="JPEG", quality=95)
|
| 71 |
+
|
| 72 |
+
buf.seek(0)
|
| 73 |
+
pdf_document.close()
|
| 74 |
+
status_text.text("Processing complete!")
|
| 75 |
+
return buf
|
| 76 |
+
|
| 77 |
+
# UI Components
|
| 78 |
+
with st.sidebar:
|
| 79 |
+
st.header("Settings")
|
| 80 |
+
dpi = st.slider("Resolution (DPI)", min_value=72, max_value=600, value=300, step=1,
|
| 81 |
+
help="Higher DPI means better quality but larger file size")
|
| 82 |
+
output_format = st.radio("Output Format", ["PNG", "JPG"],
|
| 83 |
+
help="PNG provides better quality but larger file size")
|
| 84 |
+
st.write("---")
|
| 85 |
+
st.write("### About")
|
| 86 |
+
st.write("This app converts multi-page PDFs into a single image file.")
|
| 87 |
+
st.write("Made with โค๏ธ using Streamlit and PyMuPDF")
|
| 88 |
+
|
| 89 |
+
# File uploader
|
| 90 |
+
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
| 91 |
+
|
| 92 |
+
if uploaded_file is not None:
|
| 93 |
+
# Display file info
|
| 94 |
+
file_details = {
|
| 95 |
+
"Filename": uploaded_file.name,
|
| 96 |
+
"File size": f"{uploaded_file.size / 1024:.2f} KB"
|
| 97 |
+
}
|
| 98 |
+
st.write("### File Details")
|
| 99 |
+
for k, v in file_details.items():
|
| 100 |
+
st.write(f"**{k}:** {v}")
|
| 101 |
+
|
| 102 |
+
# Save uploaded file to temp file
|
| 103 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
|
| 104 |
+
tmp_file.write(uploaded_file.getvalue())
|
| 105 |
+
pdf_path = tmp_file.name
|
| 106 |
+
|
| 107 |
+
# Process on button click
|
| 108 |
+
if st.button("Convert to Image"):
|
| 109 |
+
try:
|
| 110 |
+
with st.spinner("Converting PDF to image..."):
|
| 111 |
+
start_time = time.time()
|
| 112 |
+
|
| 113 |
+
# Process the PDF
|
| 114 |
+
img_buffer = pdf_to_single_image(pdf_path, output_format, dpi)
|
| 115 |
+
|
| 116 |
+
# Calculate processing time
|
| 117 |
+
processing_time = time.time() - start_time
|
| 118 |
+
st.success(f"Conversion completed in {processing_time:.2f} seconds!")
|
| 119 |
+
|
| 120 |
+
# Get file extension
|
| 121 |
+
ext = "png" if output_format == "PNG" else "jpg"
|
| 122 |
+
|
| 123 |
+
# Create download button
|
| 124 |
+
output_filename = f"{os.path.splitext(uploaded_file.name)[0]}.{ext}"
|
| 125 |
+
st.download_button(
|
| 126 |
+
label=f"Download {output_format} Image",
|
| 127 |
+
data=img_buffer,
|
| 128 |
+
file_name=output_filename,
|
| 129 |
+
mime=f"image/{ext.lower()}"
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# Preview (with warning for large files)
|
| 133 |
+
img = Image.open(img_buffer)
|
| 134 |
+
width, height = img.size
|
| 135 |
+
aspect_ratio = width / height
|
| 136 |
+
|
| 137 |
+
st.write("### Image Preview")
|
| 138 |
+
if height > 10000:
|
| 139 |
+
st.warning("This is a very tall image. Preview is scaled down.")
|
| 140 |
+
st.image(img, caption=f"Output Image ({width}x{height} pixels)", width=min(width, 800))
|
| 141 |
+
else:
|
| 142 |
+
st.image(img, caption=f"Output Image ({width}x{height} pixels)")
|
| 143 |
+
|
| 144 |
+
st.write(f"**Image dimensions:** {width}x{height} pixels")
|
| 145 |
+
|
| 146 |
+
except Exception as e:
|
| 147 |
+
st.error(f"An error occurred: {e}")
|
| 148 |
+
|
| 149 |
+
finally:
|
| 150 |
+
# Clean up temp file
|
| 151 |
+
if os.path.exists(pdf_path):
|
| 152 |
+
os.unlink(pdf_path)
|
| 153 |
+
else:
|
| 154 |
+
st.info("๐ Please upload a PDF file to get started.")
|
| 155 |
+
|
| 156 |
+
# Example image
|
| 157 |
+
st.write("### Example Output")
|
| 158 |
+
st.image("https://via.placeholder.com/800x600?text=PDF+to+Single+Image+Example",
|
| 159 |
+
caption="Example of converted PDF")
|
| 160 |
+
|
| 161 |
+
# Add requirements info at the bottom
|
| 162 |
+
st.write("---")
|
| 163 |
+
with st.expander("Installation Requirements"):
|
| 164 |
+
st.code("""
|
| 165 |
+
pip install streamlit PyMuPDF Pillow
|
| 166 |
+
""")
|
| 167 |
+
st.write("Run the app with: `streamlit run app.py`")
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
PyMuPDF
|
| 3 |
+
numpy
|