-
Notifications
You must be signed in to change notification settings - Fork 0
/
htmltopdf.py
103 lines (84 loc) · 2.7 KB
/
htmltopdf.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
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
96
97
98
99
100
101
102
103
import logging
import sys
from io import BytesIO
from typing import Optional, Annotated
from fastapi import FastAPI, Form
from fastapi.exception_handlers import http_exception_handler, request_validation_exception_handler
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from libs.pdf import url_to_pdf, content_to_pdf
from libs.perf import log_execution_time
# uvicorn htmltopdf:app --reload
app = FastAPI()
# https://fastapi.tiangolo.com/tutorial/cors/
origins = [
"http://localhost:8080",
]
app.add_middleware(
CORSMiddleware,
# allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
logging_format = '%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] [%(name)s:%(module)s] - %(message)s'
fileHandler = logging.FileHandler(
filename='logs/htmltopdf.log',
mode='a+', # 'a': append, 'w': overwrite
)
stream_handler = logging.StreamHandler(
stream=sys.stdout,
)
logging.basicConfig(
level=logging.DEBUG,
format=logging_format,
handlers=[
fileHandler,
stream_handler,
]
)
@app.middleware("http")
async def execution_time_middleware(request, call_next):
return await log_execution_time(request, call_next)
@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
logging.error(exc)
return await http_exception_handler(request, exc)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
logging.error(exc)
return await request_validation_exception_handler(request, exc)
@app.get("/health")
async def healthcheck():
return "OK"
@app.get("/pdf/url")
async def get_pdf_from_url(
url: str,
orientation: Optional[str] = "portrait",
filename: Optional[str] = "out",
):
pdf = await url_to_pdf(url, orientation)
return StreamingResponse(
content=BytesIO(pdf),
media_type="application/pdf",
headers={
"Content-Disposition": f"attachment;filename={filename}.pdf"
},
)
@app.post("/pdf/content")
async def get_pdf_from_content(
html: Annotated[str, Form()],
css: Annotated[str, Form()] = None,
orientation: Annotated[str, Form()] = "portrait",
filename: Annotated[str, Form()] = "out",
):
pdf = await content_to_pdf(html, css, orientation)
return StreamingResponse(
content=BytesIO(pdf),
media_type="application/pdf",
headers={
"Content-Disposition": f"attachment;filename={filename}.pdf"
},
)