File size: 2,315 Bytes
23c1fb0
 
 
41a65e8
 
 
23c1fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a65e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23c1fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41a65e8
23c1fb0
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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)