PDF-File / app.py
dschandra's picture
Update app.py
41a65e8 verified
raw
history blame
2.32 kB
from flask import Flask, request, render_template, send_file
import os
from docx2pdf import convert as docx2pdf_convert
from openpyxl import load_workbook
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
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
def convert_xlsx_to_pdf(input_file, output_file):
workbook = load_workbook(input_file)
sheet = workbook.active
c = canvas.Canvas(output_file, pagesize=letter)
width, height = letter
x_offset = 50
y_offset = height - 50
line_height = 20
for row in sheet.iter_rows(values_only=True):
x = x_offset
y = y_offset
for cell in row:
c.drawString(x, y, str(cell))
x += 100 # Adjust column width
y_offset -= line_height
if y_offset < 50:
c.showPage()
y_offset = height - 50
c.save()
@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':
convert_xlsx_to_pdf(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)