-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction_app.py
53 lines (45 loc) · 1.63 KB
/
function_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
import azure.functions as func
import logging
import pdfkit
import tempfile
import os
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
# Path to the wkhtmltopdf binary
WKHTMLTOPDF_PATH = os.path.join(os.getcwd(), 'wkhtmltopdf', 'wkhtmltopdf')
@app.route(route="dpcpdfmerger")
def dpcpdfmerger(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
try:
req_body = req.get_json()
except ValueError:
return func.HttpResponse(
"Invalid JSON body.",
status_code=400
)
html_content = req_body.get('html')
if not html_content:
return func.HttpResponse(
"Please provide HTML content in the request body.",
status_code=400
)
try:
# Configure pdfkit to use the local wkhtmltopdf binary
config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_PATH)
# Create a temporary file to store the PDF
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
pdfkit.from_string(html_content, temp_pdf.name, configuration=config)
temp_pdf.seek(0)
pdf_data = temp_pdf.read()
return func.HttpResponse(
pdf_data,
mimetype='application/pdf',
headers={
'Content-Disposition': 'attachment; filename="output.pdf"'
}
)
except Exception as e:
logging.error(f"Error converting HTML to PDF: {e}")
return func.HttpResponse(
"An error occurred while converting HTML to PDF.",
status_code=500
)