Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,11 +3,21 @@ from PyPDF2 import PdfReader
|
|
3 |
from docx import Document
|
4 |
from io import BytesIO
|
5 |
|
6 |
-
def pdf_to_word(pdf_file):
|
7 |
-
"""Convert a PDF file to a Word file."""
|
8 |
reader = PdfReader(pdf_file)
|
9 |
-
document = Document()
|
10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
for page in reader.pages:
|
12 |
if page.extract_text(): # Ensure text is extracted
|
13 |
text = page.extract_text()
|
@@ -29,11 +39,12 @@ st.write("Upload a PDF file, and we will convert it into a Word document for you
|
|
29 |
|
30 |
# File uploader
|
31 |
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
|
|
32 |
|
33 |
if uploaded_file is not None:
|
34 |
with st.spinner("Converting PDF to Word..."):
|
35 |
try:
|
36 |
-
word_file = pdf_to_word(uploaded_file)
|
37 |
st.success("Conversion successful!")
|
38 |
st.download_button(
|
39 |
label="Download Word file",
|
@@ -41,5 +52,6 @@ if uploaded_file is not None:
|
|
41 |
file_name="converted.docx",
|
42 |
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
43 |
)
|
44 |
-
except
|
45 |
-
st.error(
|
|
|
|
3 |
from docx import Document
|
4 |
from io import BytesIO
|
5 |
|
6 |
+
def pdf_to_word(pdf_file, password=None):
|
7 |
+
"""Convert a PDF file to a Word file with optional decryption."""
|
8 |
reader = PdfReader(pdf_file)
|
|
|
9 |
|
10 |
+
# Decrypt the PDF if it's encrypted
|
11 |
+
if reader.is_encrypted:
|
12 |
+
if password:
|
13 |
+
try:
|
14 |
+
reader.decrypt(password)
|
15 |
+
except Exception as e:
|
16 |
+
raise ValueError("Failed to decrypt the PDF. Check the password.") from e
|
17 |
+
else:
|
18 |
+
raise ValueError("The PDF is encrypted. Please provide a password.")
|
19 |
+
|
20 |
+
document = Document()
|
21 |
for page in reader.pages:
|
22 |
if page.extract_text(): # Ensure text is extracted
|
23 |
text = page.extract_text()
|
|
|
39 |
|
40 |
# File uploader
|
41 |
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
42 |
+
password = st.text_input("Enter password (if the PDF is encrypted):", type="password")
|
43 |
|
44 |
if uploaded_file is not None:
|
45 |
with st.spinner("Converting PDF to Word..."):
|
46 |
try:
|
47 |
+
word_file = pdf_to_word(uploaded_file, password)
|
48 |
st.success("Conversion successful!")
|
49 |
st.download_button(
|
50 |
label="Download Word file",
|
|
|
52 |
file_name="converted.docx",
|
53 |
mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
54 |
)
|
55 |
+
except ValueError as ve:
|
56 |
+
st.error(str(ve))
|
57 |
+
ex
|