File size: 1,804 Bytes
a0dcf2b
 
f3f2c2f
 
a0dcf2b
f3f2c2f
 
a0dcf2b
 
f3f2c2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pdfplumber
import pandas as pd
from io import BytesIO

def extract_tables_from_pdf(pdf_file):
    tables = []
    with pdfplumber.open(pdf_file) as pdf:
        for page in pdf.pages:
            extracted_tables = page.extract_tables()
            for table in extracted_tables:
                tables.append(pd.DataFrame(table))
    
    if not tables:
        return None
    
    # Concatenate all tables into one DataFrame
    final_df = pd.concat(tables, ignore_index=True)
    
    # Set first row as column headers (if applicable)
    final_df.columns = final_df.iloc[0]  # First row as headers
    final_df = final_df[1:].reset_index(drop=True)
    
    return final_df

def convert_to_excel(dataframe):
    output = BytesIO()
    with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
        dataframe.to_excel(writer, index=False, sheet_name='Sheet1')
    output.seek(0)
    return output

# Streamlit UI
st.title("PDF to Excel Converter")
st.write("Upload a PDF file with tabular data, and it will be converted into an Excel file.")

uploaded_file = st.file_uploader("Choose a PDF file", type=["pdf"])

if uploaded_file is not None:
    with st.spinner("Extracting tables from PDF..."):
        df = extract_tables_from_pdf(uploaded_file)
        
        if df is not None:
            st.write("### Extracted Table Preview")
            st.dataframe(df)
            
            excel_data = convert_to_excel(df)
            st.download_button(label="Download Excel File", 
                               data=excel_data, 
                               file_name="converted.xlsx", 
                               mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        else:
            st.error("No tables found in the PDF.")