-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
58 lines (44 loc) · 1.35 KB
/
app.py
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
from flask import Flask, request, send_file, render_template
import pymupdf
import io
import zipfile
app = Flask(__name__)
@app.route("/")
def upload_form():
return render_template("index.html")
@app.route("/upload", methods=["POST"])
def convert_pdf():
pdf_file = request.files['file']
pdf_data = pdf_file.read()
doc = pymupdf.open("pdf", pdf_data)
images = []
for page in doc:
pix = page.get_pixmap()
img_data = pix.tobytes("png")
images.append(img_data)
filename = pdf_file.filename.split(".")[0]
if len(images) > 1:
zip_io = io.BytesIO()
with zipfile.ZipFile(
zip_io, mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=9
) as zip_archive:
for i, image in enumerate(images):
zip_archive.writestr(f"{filename}_{i+1}.png", image)
zip_io.seek(0)
return send_file(
zip_io,
mimetype="application/zip",
as_attachment=True,
download_name=f"{filename}.zip",
)
else:
img_io = io.BytesIO(images[0])
img_io.seek(0)
return send_file(
img_io,
mimetype="image/png",
as_attachment=True,
download_name=f"{filename}.png",
)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)