-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.py
More file actions
95 lines (77 loc) · 2.6 KB
/
server.py
File metadata and controls
95 lines (77 loc) · 2.6 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
from tempfile import NamedTemporaryFile
from subprocess import run
from flask import Flask, request, jsonify, send_file
app = Flask(__name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
@app.route("/health", methods=["GET"])
def health():
return jsonify({"status": "ok"}), 200
@app.route("/doc_to_pdf", methods=["GET", "POST"])
def upload_file():
if request.method == "GET":
return """
<!doctype html>
<head>
<meta charset="utf-8">
<title>Convert Microsoft Word (DOC/DOCX) to PDF</title>
</head>
<body>
<h1>Upload new File</h1>
<form id="upload-form" method="post" enctype="multipart/form-data">
<label for="file_input">Choose a file:</label>
<input id="file_input" type="file" name="file" required>
<button id="submit_form" type="submit">Upload</button>
</form>
</body>
</html>
"""
if "file" not in request.files:
return jsonify({"message": "No file part in the request"}), 400
file = request.files["file"]
if file.filename == "":
return jsonify({"message": "No file selected for uploading"}), 400
docx_file = NamedTemporaryFile(delete=False, suffix=".docx", dir=BASE_DIR)
pdf_path = f"{docx_file.name[:-5]}.pdf"
try:
file.save(docx_file.name)
docx_file.close()
result = run(
[
"libreoffice",
"--headless",
"--convert-to",
"pdf",
"--outdir",
BASE_DIR,
docx_file.name,
],
capture_output=True,
text=True,
check=True,
)
if not os.path.exists(pdf_path):
return (
jsonify(
{
"message": "PDF was not generated. Verify that the input is a valid DOCX file.",
"stdout": result.stdout,
"stderr": result.stderr,
}
),
500,
)
return send_file(
pdf_path,
download_name=os.path.basename(pdf_path),
as_attachment=True,
)
except Exception as e:
return jsonify({"message": "Conversion failed", "error": str(e)}), 500
finally:
if os.path.exists(docx_file.name):
os.remove(docx_file.name)
if os.path.exists(pdf_path):
os.remove(pdf_path)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)