besimabdullai's picture
Update src/app.py
b0b32ea verified
Raw History Blame Contribute Delete
32.8 kB
import io import os import zipfile from typing import List import streamlit as st from PIL import Image, ImageOps from pdf2image import convert_from_bytes, pdfinfo_from_bytes # ============================================================ # PAGE CONFIGURATION # ============================================================ st.set_page_config( page_title="PDF Page β†’ Image Converter", page_icon="πŸ“„", layout="wide", initial_sidebar_state="expanded", ) # ============================================================ # SESSION STATE # ============================================================ if "conversion_ready" not in st.session_state: st.session_state.conversion_ready = False if "converted_png" not in st.session_state: st.session_state.converted_png = None if "converted_jpeg" not in st.session_state: st.session_state.converted_jpeg = None if "png_filename" not in st.session_state: st.session_state.png_filename = None if "jpeg_filename" not in st.session_state: st.session_state.jpeg_filename = None if "converted_zip" not in st.session_state: st.session_state.converted_zip = None if "zip_filename" not in st.session_state: st.session_state.zip_filename = None if "final_image" not in st.session_state: st.session_state.final_image = None if "result_page" not in st.session_state: st.session_state.result_page = None if "result_dpi" not in st.session_state: st.session_state.result_dpi = None if "result_width" not in st.session_state: st.session_state.result_width = None if "result_height" not in st.session_state: st.session_state.result_height = None if "original_width" not in st.session_state: st.session_state.original_width = None if "original_height" not in st.session_state: st.session_state.original_height = None # ============================================================ # HELPER FUNCTIONS # ============================================================ def get_pdf_page_count(pdf_bytes: bytes) -> int: info = pdfinfo_from_bytes(pdf_bytes) return int(info["Pages"]) def clean_filename(filename: str) -> str: return os.path.splitext(filename)[0] def crop_to_fit( image: Image.Image, target_width: int, target_height: int, ) -> Image.Image: return ImageOps.fit( image, (int(target_width), int(target_height)), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5), ) def image_to_bytes( image: Image.Image, output_format: str = "PNG", jpeg_quality: int = 95, ) -> bytes: buffer = io.BytesIO() if output_format.upper() == "JPEG": if image.mode != "RGB": image = image.convert("RGB") image.save( buffer, format="JPEG", quality=jpeg_quality, optimize=True, ) else: image.save( buffer, format="PNG", optimize=True, ) buffer.seek(0) return buffer.getvalue() def convert_single_page( pdf_bytes: bytes, page_number: int, dpi: int, ) -> Image.Image: images = convert_from_bytes( pdf_bytes, dpi=dpi, first_page=page_number, last_page=page_number, fmt="png", thread_count=1, ) if not images: raise RuntimeError( f"Could not convert page {page_number}." ) return images[0] def convert_page_range( pdf_bytes: bytes, first_page: int, last_page: int, dpi: int, ) -> List[Image.Image]: return convert_from_bytes( pdf_bytes, dpi=dpi, first_page=first_page, last_page=last_page, fmt="png", thread_count=2, ) def resize_images( images: List[Image.Image], target_width: int, target_height: int, ) -> List[Image.Image]: return [ crop_to_fit( image=image, target_width=target_width, target_height=target_height, ) for image in images ] def create_multi_page_zip( images: List[Image.Image], first_page: int, base_filename: str, dpi: int, target_width: int, target_height: int, generate_png: bool, generate_jpeg: bool, jpeg_quality: int, ) -> bytes: zip_buffer = io.BytesIO() with zipfile.ZipFile( zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED, ) as zip_file: for index, image in enumerate(images): page_number = first_page + index filename_base = ( f"{base_filename}" f"_page_{page_number}" f"_{target_width}x{target_height}px" f"_{dpi}dpi" ) if generate_png: png_bytes = image_to_bytes( image=image, output_format="PNG", jpeg_quality=jpeg_quality, ) zip_file.writestr( f"{filename_base}.png", png_bytes, ) if generate_jpeg: jpeg_bytes = image_to_bytes( image=image, output_format="JPEG", jpeg_quality=jpeg_quality, ) zip_file.writestr( f"{filename_base}.jpg", jpeg_bytes, ) zip_buffer.seek(0) return zip_buffer.getvalue() def create_single_page_zip( image: Image.Image, base_filename: str, page_number: int, dpi: int, target_width: int, target_height: int, generate_png: bool, generate_jpeg: bool, jpeg_quality: int, ) -> bytes: """ Create one ZIP containing PNG and/or JPEG versions of a single converted page. """ zip_buffer = io.BytesIO() filename_base = ( f"{base_filename}" f"_page_{page_number}" f"_{target_width}x{target_height}px" f"_{dpi}dpi" ) with zipfile.ZipFile( zip_buffer, mode="w", compression=zipfile.ZIP_DEFLATED, ) as zip_file: if generate_png: png_bytes = image_to_bytes( image=image, output_format="PNG", jpeg_quality=jpeg_quality, ) zip_file.writestr( f"{filename_base}.png", png_bytes, ) if generate_jpeg: jpeg_bytes = image_to_bytes( image=image, output_format="JPEG", jpeg_quality=jpeg_quality, ) zip_file.writestr( f"{filename_base}.jpg", jpeg_bytes, ) zip_buffer.seek(0) return zip_buffer.getvalue() def human_file_size(size_bytes: int) -> str: if size_bytes < 1024: return f"{size_bytes} B" if size_bytes < 1024 * 1024: return f"{size_bytes / 1024:.1f} KB" return f"{size_bytes / (1024 * 1024):.2f} MB" def clear_single_page_result(): st.session_state.conversion_ready = False st.session_state.converted_png = None st.session_state.converted_jpeg = None st.session_state.converted_zip = None st.session_state.png_filename = None st.session_state.jpeg_filename = None st.session_state.zip_filename = None st.session_state.final_image = None st.session_state.result_page = None st.session_state.result_dpi = None st.session_state.result_width = None st.session_state.result_height = None st.session_state.original_width = None st.session_state.original_height = None # ============================================================ # CUSTOM STYLING # ============================================================ st.markdown( """ <style> .block-container { max-width: 1200px; padding-top: 2rem; padding-bottom: 3rem; } .main-title { font-size: 2.4rem; font-weight: 700; margin-bottom: 0.25rem; } .subtitle { color: #666; font-size: 1.05rem; margin-bottom: 2rem; } </style> """, unsafe_allow_html=True, ) # ============================================================ # HEADER # ============================================================ st.markdown( '<div class="main-title">πŸ“„ PDF Page β†’ Image Converter</div>', unsafe_allow_html=True, ) st.markdown( """ <div class="subtitle"> Convert PDF pages into exact-size PNG and/or JPEG images. <br><br> Author: Mag Besim Verdi Abdullai, PhD DBA St., Copyright Β© 2026 </div> """, unsafe_allow_html=True, ) # ============================================================ # SIDEBAR # ============================================================ with st.sidebar: st.header("βš™οΈ Conversion Settings") dpi = st.select_slider( "Resolution (DPI)", options=[ 72, 100, 120, 150, 200, 250, 300, 400, 600, ], value=300, help=( "The PDF page is first rendered at this " "resolution before being resized." ), ) st.divider() st.subheader("πŸ“ Final Image Size") size_col1, size_col2 = st.columns(2) with size_col1: target_width = st.number_input( "Width (px)", min_value=1, max_value=10000, value=297, step=1, ) with size_col2: target_height = st.number_input( "Height (px)", min_value=1, max_value=10000, value=422, step=1, ) target_width = int(target_width) target_height = int(target_height) st.caption( f"Final output: " f"{target_width} Γ— {target_height} px" ) st.caption( "Crop-to-Fit preserves the aspect ratio and crops " "excess edges to create the exact requested size." ) st.divider() st.subheader("πŸ–ΌοΈ Output Formats") generate_png = st.checkbox( "PNG", value=True, ) generate_jpeg = st.checkbox( "JPEG", value=True, ) jpeg_quality = st.slider( "JPEG quality", min_value=50, max_value=100, value=95, step=1, disabled=not generate_jpeg, ) st.divider() st.caption( "Recommended: 150 DPI for screen use and " "300 DPI for high-quality output." ) st.caption( "Higher DPI values use more memory " "and take longer to process." ) # ============================================================ # FILE UPLOAD # ============================================================ uploaded_file = st.file_uploader( "Upload a PDF", type=["pdf"], accept_multiple_files=False, help="Select a PDF document from your computer.", ) # ============================================================ # NO FILE # ============================================================ if uploaded_file is None: clear_single_page_result() st.info( "Upload a PDF file above to begin converting pages." ) st.markdown( """ ### Features - Convert individual PDF pages - Convert page ranges - Convert an entire PDF - Select rendering DPI - Define exact output width and height - Crop-to-Fit resizing - Generate PNG - Generate JPEG - Generate PNG and JPEG together - Download PNG and JPEG individually - Download multiple pages as ZIP """ ) st.stop() # ============================================================ # READ PDF # ============================================================ try: pdf_bytes = uploaded_file.getvalue() if not pdf_bytes: st.error( "The uploaded PDF is empty." ) st.stop() with st.spinner( "Reading PDF information..." ): page_count = get_pdf_page_count( pdf_bytes ) except Exception as exc: st.error( "The PDF could not be opened." ) st.exception(exc) st.info( "Make sure Poppler is installed in your Docker image " "using the package `poppler-utils`." ) st.stop() # ============================================================ # BASE FILENAME # ============================================================ base_filename = clean_filename( uploaded_file.name ) # ============================================================ # DOCUMENT INFORMATION # ============================================================ st.success( f"{uploaded_file.name} loaded successfully β€” " f"{page_count} page" f"{'' if page_count == 1 else 's'}." ) info_col1, info_col2, info_col3, info_col4 = st.columns(4) with info_col1: st.metric( "Pages", page_count, ) with info_col2: st.metric( "PDF size", human_file_size( len(pdf_bytes) ), ) with info_col3: st.metric( "Resolution", f"{dpi} DPI", ) with info_col4: st.metric( "Final size", f"{target_width} Γ— {target_height} px", ) st.divider() # ============================================================ # OUTPUT VALIDATION # ============================================================ if not generate_png and not generate_jpeg: st.warning( "Please select at least one output format: PNG or JPEG." ) # ============================================================ # CONVERSION MODE # ============================================================ conversion_mode = st.radio( "Conversion mode", options=[ "Single page", "Page range", "Entire PDF", ], horizontal=True, ) # ============================================================ # SINGLE PAGE # ============================================================ if conversion_mode == "Single page": st.subheader("Select PDF Page") page_number = st.number_input( "Page number", min_value=1, max_value=page_count, value=1, step=1, ) page_number = int(page_number) st.subheader("Convert to image") if st.button( "πŸš€ Convert PDF Page", type="primary", use_container_width=True, disabled=( not generate_png and not generate_jpeg ), ): try: clear_single_page_result() # ------------------------------------------------ # RENDER # ------------------------------------------------ with st.spinner( f"Rendering page {page_number} " f"at {dpi} DPI..." ): rendered_image = convert_single_page( pdf_bytes=pdf_bytes, page_number=page_number, dpi=dpi, ) original_width = rendered_image.width original_height = rendered_image.height # ------------------------------------------------ # RESIZE # ------------------------------------------------ with st.spinner( f"Creating " f"{target_width} Γ— " f"{target_height} px image..." ): final_image = crop_to_fit( image=rendered_image, target_width=target_width, target_height=target_height, ) # ------------------------------------------------ # FILENAME # ------------------------------------------------ filename_base = ( f"{base_filename}" f"_page_{page_number}" f"_{target_width}x{target_height}px" f"_{dpi}dpi" ) # ------------------------------------------------ # SAVE PNG TO SESSION STATE # ------------------------------------------------ if generate_png: st.session_state.converted_png = image_to_bytes( image=final_image, output_format="PNG", jpeg_quality=jpeg_quality, ) st.session_state.png_filename = ( f"{filename_base}.png" ) # ------------------------------------------------ # SAVE JPEG TO SESSION STATE # ------------------------------------------------ if generate_jpeg: st.session_state.converted_jpeg = image_to_bytes( image=final_image, output_format="JPEG", jpeg_quality=jpeg_quality, ) st.session_state.jpeg_filename = ( f"{filename_base}.jpg" ) # ------------------------------------------------ # CREATE ZIP FILE # ------------------------------------------------ st.session_state.converted_zip = create_single_page_zip( image=final_image, base_filename=base_filename, page_number=page_number, dpi=dpi, target_width=target_width, target_height=target_height, generate_png=generate_png, generate_jpeg=generate_jpeg, jpeg_quality=jpeg_quality, ) st.session_state.zip_filename = ( f"{filename_base}.zip" ) # ------------------------------------------------ # SAVE RESULT INFORMATION # ------------------------------------------------ st.session_state.final_image = final_image st.session_state.original_width = ( original_width ) st.session_state.original_height = ( original_height ) st.session_state.result_page = ( page_number ) st.session_state.result_dpi = ( dpi ) st.session_state.result_width = ( target_width ) st.session_state.result_height = ( target_height ) st.session_state.conversion_ready = True except Exception as exc: st.error( f"Could not convert page {page_number}." ) st.exception(exc) # ======================================================== # PERSISTENT RESULT # ======================================================== if st.session_state.conversion_ready: st.success( f"Page {st.session_state.result_page} " f"converted successfully." ) result_col1, result_col2 = st.columns(2) with result_col1: st.metric( "Rendered image", ( f"{st.session_state.original_width} Γ— " f"{st.session_state.original_height} px" ), ) with result_col2: st.metric( "Final image", ( f"{st.session_state.result_width} Γ— " f"{st.session_state.result_height} px" ), ) st.caption( f"Page {st.session_state.result_page} β†’ " f"{st.session_state.result_dpi} DPI β†’ " f"Crop-to-Fit β†’ " f"{st.session_state.result_width} Γ— " f"{st.session_state.result_height} px" ) # ---------------------------------------------------- # PREVIEW # ---------------------------------------------------- st.subheader( f"Preview β€” Page " f"{st.session_state.result_page}" ) st.image( st.session_state.final_image, caption=( f"{st.session_state.result_width} Γ— " f"{st.session_state.result_height} px" ), use_container_width=False, ) # ==================================================== # DOWNLOAD # ==================================================== st.subheader("Download") if ( st.session_state.converted_png is not None and st.session_state.converted_jpeg is not None ): download_col1, download_col2, download_col3 = st.columns(3) with download_col1: st.download_button( label="⬇️ Download PNG", data=st.session_state.converted_png, file_name=st.session_state.png_filename, mime="image/png", use_container_width=True, key="single_download_png", ) st.caption( st.session_state.png_filename ) with download_col2: st.download_button( label="⬇️ Download JPEG", data=st.session_state.converted_jpeg, file_name=st.session_state.jpeg_filename, mime="image/jpeg", use_container_width=True, key="single_download_jpeg", ) st.caption( st.session_state.jpeg_filename ) with download_col3: st.download_button( label="πŸ“¦ Download ZIP File", data=st.session_state.converted_zip, file_name=st.session_state.zip_filename, mime="application/zip", use_container_width=True, key="single_download_zip_both", ) st.caption( st.session_state.zip_filename ) elif st.session_state.converted_png is not None: download_col1, download_col2 = st.columns(2) with download_col1: st.download_button( label="⬇️ Download PNG", data=st.session_state.converted_png, file_name=st.session_state.png_filename, mime="image/png", use_container_width=True, key="single_download_png_only", ) st.caption( st.session_state.png_filename ) with download_col2: st.download_button( label="πŸ“¦ Download ZIP File", data=st.session_state.converted_zip, file_name=st.session_state.zip_filename, mime="application/zip", use_container_width=True, key="single_download_zip_png", ) st.caption( st.session_state.zip_filename ) elif st.session_state.converted_jpeg is not None: download_col1, download_col2 = st.columns(2) with download_col1: st.download_button( label="⬇️ Download JPEG", data=st.session_state.converted_jpeg, file_name=st.session_state.jpeg_filename, mime="image/jpeg", use_container_width=True, key="single_download_jpeg_only", ) st.caption( st.session_state.jpeg_filename ) with download_col2: st.download_button( label="πŸ“¦ Download ZIP File", data=st.session_state.converted_zip, file_name=st.session_state.zip_filename, mime="application/zip", use_container_width=True, key="single_download_zip_jpeg", ) st.caption( st.session_state.zip_filename ) # ============================================================ # PAGE RANGE # ============================================================ elif conversion_mode == "Page range": col1, col2 = st.columns(2) with col1: first_page = st.number_input( "First page", min_value=1, max_value=page_count, value=1, step=1, ) with col2: default_last = min( page_count, 5, ) last_page = st.number_input( "Last page", min_value=1, max_value=page_count, value=default_last, step=1, ) first_page = int(first_page) last_page = int(last_page) selected_pages = ( last_page - first_page + 1 ) if first_page > last_page: st.error( "The first page cannot be greater " "than the last page." ) else: st.caption( f"{selected_pages} page" f"{'' if selected_pages == 1 else 's'} selected." ) if selected_pages > 20: st.warning( "You selected more than 20 pages. " "High DPI conversion may use significant memory." ) if st.button( "πŸš€ Convert Page Range", type="primary", use_container_width=True, disabled=( not generate_png and not generate_jpeg ), ): try: with st.spinner( f"Converting pages " f"{first_page}–{last_page}..." ): images = convert_page_range( pdf_bytes=pdf_bytes, first_page=first_page, last_page=last_page, dpi=dpi, ) images = resize_images( images=images, target_width=target_width, target_height=target_height, ) zip_bytes = create_multi_page_zip( images=images, first_page=first_page, base_filename=base_filename, dpi=dpi, target_width=target_width, target_height=target_height, generate_png=generate_png, generate_jpeg=generate_jpeg, jpeg_quality=jpeg_quality, ) st.success( f"Converted {len(images)} pages successfully." ) st.subheader("Download") st.download_button( label="⬇️ Download Selected Formats", data=zip_bytes, file_name=( f"{base_filename}" f"_pages_{first_page}_to_{last_page}" f"_{target_width}x{target_height}px" f"_{dpi}dpi.zip" ), mime="application/zip", use_container_width=True, ) st.subheader("Preview") for index, image in enumerate(images): current_page = ( first_page + index ) with st.expander( f"Page {current_page} β€” " f"{target_width} Γ— " f"{target_height} px", expanded=index == 0, ): st.image( image, use_container_width=False, ) except Exception as exc: st.error( "Could not convert the selected page range." ) st.exception(exc) # ============================================================ # ENTIRE PDF # ============================================================ else: st.write( f"This will convert all **{page_count} pages**." ) st.write( f"Final dimensions: " f"**{target_width} Γ— {target_height} px**" ) if page_count > 20: st.warning( "This PDF contains many pages. " "Converting the entire document at high DPI " "may consume significant memory." ) if page_count > 50: st.warning( "For large PDFs, consider using Page range mode " "and processing the document in smaller sections." ) confirm_conversion = st.checkbox( "I want to convert the entire PDF" ) if st.button( "πŸš€ Convert Entire PDF", type="primary", use_container_width=True, disabled=( not confirm_conversion or ( not generate_png and not generate_jpeg ) ), ): try: with st.spinner( f"Converting all {page_count} pages..." ): images = convert_page_range( pdf_bytes=pdf_bytes, first_page=1, last_page=page_count, dpi=dpi, ) images = resize_images( images=images, target_width=target_width, target_height=target_height, ) zip_bytes = create_multi_page_zip( images=images, first_page=1, base_filename=base_filename, dpi=dpi, target_width=target_width, target_height=target_height, generate_png=generate_png, generate_jpeg=generate_jpeg, jpeg_quality=jpeg_quality, ) st.success( f"Successfully converted " f"{len(images)} pages." ) st.subheader("Download") st.download_button( label="⬇️ Download Selected Formats", data=zip_bytes, file_name=( f"{base_filename}" f"_all_pages" f"_{target_width}x{target_height}px" f"_{dpi}dpi.zip" ), mime="application/zip", use_container_width=True, ) st.subheader("Preview") preview_count = min( len(images), 10, ) for index in range(preview_count): page_number = index + 1 image = images[index] with st.expander( f"Page {page_number} β€” " f"{target_width} Γ— " f"{target_height} px", expanded=index == 0, ): st.image( image, use_container_width=False, ) if len(images) > preview_count: st.info( f"Showing the first {preview_count} pages only. " f"The ZIP contains all {len(images)} " f"converted pages." ) except Exception as exc: st.error( "Could not convert the complete PDF." ) st.exception(exc) # ============================================================ # FOOTER # ============================================================ st.divider() st.caption( "PDF Page β†’ Image Converter β€’ " "Author Mag. Besim Verdi Abdullai, MBM, PGP, MA, PhD Student" "Copyright Β© 2026" )
import io
import os
import zipfile
from typing import List
import streamlit as st
from PIL import Image, ImageOps
from pdf2image import convert_from_bytes, pdfinfo_from_bytes
# ============================================================
# PAGE CONFIGURATION
# ============================================================
st.set_page_config(
page_title="PDF Page β†’ Image Converter",
page_icon="πŸ“„",
layout="wide",
initial_sidebar_state="expanded",
)
# ============================================================
# SESSION STATE
# ============================================================
if "conversion_ready" not in st.session_state:
st.session_state.conversion_ready = False
if "converted_png" not in st.session_state:
st.session_state.converted_png = None
if "converted_jpeg" not in st.session_state:
st.session_state.converted_jpeg = None
if "png_filename" not in st.session_state:
st.session_state.png_filename = None
if "jpeg_filename" not in st.session_state:
st.session_state.jpeg_filename = None
if "converted_zip" not in st.session_state:
st.session_state.converted_zip = None
if "zip_filename" not in st.session_state:
st.session_state.zip_filename = None
if "final_image" not in st.session_state:
st.session_state.final_image = None
if "result_page" not in st.session_state:
st.session_state.result_page = None
if "result_dpi" not in st.session_state:
st.session_state.result_dpi = None
if "result_width" not in st.session_state:
st.session_state.result_width = None
if "result_height" not in st.session_state:
st.session_state.result_height = None
if "original_width" not in st.session_state:
st.session_state.original_width = None
if "original_height" not in st.session_state:
st.session_state.original_height = None
# ============================================================
# HELPER FUNCTIONS
# ============================================================
def get_pdf_page_count(pdf_bytes: bytes) -> int:
info = pdfinfo_from_bytes(pdf_bytes)
return int(info["Pages"])
def clean_filename(filename: str) -> str:
return os.path.splitext(filename)[0]
def crop_to_fit(
image: Image.Image,
target_width: int,
target_height: int,
) -> Image.Image:
return ImageOps.fit(
image,
(int(target_width), int(target_height)),
method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5),
)
def image_to_bytes(
image: Image.Image,
output_format: str = "PNG",
jpeg_quality: int = 95,
) -> bytes: