/
app.py
38 lines (31 loc) · 1.13 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
from ast import Bytes
from fastapi import FastAPI, UploadFile, File
from starlette.middleware.cors import CORSMiddleware
import img2pdf
from typing import List
from fastapi.responses import Response
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://img2pdf.seigo2016.com"],
allow_credentials=False,
allow_methods=["get","post"],
allow_headers=["*"]
)
@app.post('/convert')
async def get_file(filename: str="default.pdf", files: List[UploadFile] = File(...)) -> Response:
if not filename.endswith(".pdf"):
filename = filename + ".pdf"
data: List[Bytes] = []
for f in files:
if not (f.content_type == "image/jpeg" or f.content_type == "image/png"):
return Response(status_code=400, content="Only jpeg and png files are allowed")
d = await f.read()
data.append(d)
pdf_data:Bytes = img2pdf.convert(data)
headers = {
'Content-Disposition': f'attachment; filename="{filename}"'
}
return Response(content=pdf_data, headers=headers, media_type="application/pdf")