File size: 2,332 Bytes
d8f0819
 
a1f3ddf
 
d8f0819
 
 
 
a1f3ddf
d8f0819
 
 
 
 
 
 
a1f3ddf
d8f0819
 
 
 
 
 
a1f3ddf
d8f0819
a1f3ddf
 
 
 
 
 
d8f0819
 
 
 
 
 
a1f3ddf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
import streamlit as st
from PIL import Image
import pdfkit
import os

# Function to process a single image with user-provided sequence number
def process_image(image_file, sequence_number):
    image = Image.open(image_file)
    return image, sequence_number

# Function to generate the PDF
def generate_pdf(images_with_sequence):
    pdf_name = "output.pdf"

    images_with_sequence.sort(key=lambda x: x[1])

    config = pdfkit.configuration(wkhtmltopdf=r'/usr/bin/wkhtmltopdf') #provide your wkhtmltopdf path here
    pdf_options = {
        "margin-top": "0.5in",
        "margin-right": "0.5in",
        "margin-bottom": "0.5in",
        "margin-left": "0.5in",
        "encoding": "UTF-8",
        "dpi": 300,
    }
    try:
        pdfkit.from_file([image[0] for image in images_with_sequence], pdf_name, options=pdf_options, configuration=config)
        return pdf_name
    except Exception as e:
        st.error(f"Error generating PDF: {e}")
        return None

st.title("Image to PDF Converter (Multiple Images)")

uploaded_images = st.file_uploader("Upload Images", type=["jpg", "jpeg", "png"], accept_multiple=True)

if uploaded_images:
    num_images = len(uploaded_images)
    if num_images > 0: #check if any image is uploaded
        images_with_sequence = []

        for i, image_file in enumerate(uploaded_images):
            st.image(image_file, width=250)
            sequence_options = [str(j) for j in range(1, num_images + 1)]
            default_index = i #set default selection of sequence as the order of upload
            sequence_number = st.selectbox(f"Sequence Number for Image {i+1}", sequence_options, index = default_index)
            processed_image, processed_sequence = process_image(image_file, int(sequence_number))
            images_with_sequence.append((processed_image, processed_sequence))

        if st.button("Generate PDF"):
            pdf_name = generate_pdf(images_with_sequence)
            if pdf_name: #check if pdf is generated successfully
                st.success(f"PDF generated! Download: {pdf_name}")
                with open(pdf_name, "rb") as pdf_file:
                    st.download_button("Download PDF", pdf_file, file_name=pdf_name)
                os.remove(pdf_name) #remove the file after download
else:
    st.write("Please upload images to continue")