PDFConverter / app.py
BeamBullet's picture
Upload
6f8b89f verified
from flask import Flask, request, send_file
from pdf2docx import Converter
import os
app = Flask(__name__)
UPLOAD_FOLDER = './uploads'
CONVERTED_FOLDER = './converted'
ALLOWED_EXTENSIONS = {'pdf'}
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
if not os.path.exists(CONVERTED_FOLDER):
os.makedirs(CONVERTED_FOLDER)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def upload_form():
return '''
<!doctype html>
<title>Upload a PDF to Convert</title>
<h1>Upload a PDF to Convert to Word</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''
@app.route('/', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
if file.filename == '':
return 'No selected file'
if file and allowed_file(file.filename):
filepath = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(filepath)
docx_filename = os.path.splitext(file.filename)[0] + '.docx'
docx_filepath = os.path.join(CONVERTED_FOLDER, docx_filename)
converter = Converter(filepath)
converter.convert(docx_filepath)
converter.close()
os.remove(filepath) # Remove the uploaded PDF
return send_file(docx_filepath, as_attachment=True)
return 'Invalid file type'
if __name__ == '__main__':
app.run(debug=True)