PDF-File / app.py
dschandra's picture
Create app.py
23c1fb0 verified
raw
history blame
1.62 kB
from flask import Flask, request, render_template, send_file
import os
from docx2pdf import convert as docx2pdf_convert
from xlsx2pdf import xlsx2pdf
app = Flask(__name__)
UPLOAD_FOLDER = 'uploads'
CONVERTED_FOLDER = 'converted'
# Ensure upload and converted directories exist
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
if not os.path.exists(CONVERTED_FOLDER):
os.makedirs(CONVERTED_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['CONVERTED_FOLDER'] = CONVERTED_FOLDER
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file:
file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(file_path)
# Convert the file to PDF based on its extension
file_extension = file.filename.split('.')[-1].lower()
converted_file_path = os.path.join(app.config['CONVERTED_FOLDER'], f"{os.path.splitext(file.filename)[0]}.pdf")
try:
if file_extension == 'doc' or file_extension == 'docx':
docx2pdf_convert(file_path, converted_file_path)
elif file_extension == 'xlsx':
xlsx2pdf(file_path, converted_file_path)
else:
return "Unsupported file type!"
return send_file(converted_file_path, as_attachment=True)
except Exception as e:
return str(e)
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)