I created an Azure Function that writes user data into specific fields of a pdf and returns that pdf as a response to the client. However, I always get a 500 error code, even though all the steps up until the last seem to work just fine and it also runs locally without issue.
Here’s my init.py:
JavaScript
x
26
26
1
import logging
2
3
import azure.functions as func
4
from PyPDF2 import PdfFileReader, PdfFileWriter
5
6
7
def main(req: func.HttpRequest) -> func.HttpResponse:
8
logging.info('----- Python HTTP trigger function processed a request. -----')
9
10
BLOB_NAME = 'sheet.pdf'
11
12
reader = PdfFileReader(BLOB_NAME)
13
writer = PdfFileWriter()
14
15
page = reader.pages[0]
16
17
writer.addPage(page)
18
19
sheetData = {}
20
sheetData["Full Name"] = "Name"
21
22
writer.updatePageFormFieldValues(writer.getPage(0), sheetData)
23
24
return func.HttpResponse(writer, mimetype="application/pdf")
25
26
I can return things like str(writer.getPage(0))
instead of writer
so I assume my requirements.txt works fine. It only fails when returning the HttpResponse without a body of type string. I thought adding the correct mime-type would solve the problem but it returns the same status code. I’m kind of clueless at this point.
Advertisement
Answer
Try creating a bytes object to return:
JavaScript
1
10
10
1
import io
2
3
pdf_bytes = io.BytesIO()
4
5
writer.write(pdf_bytes)
6
pdf_bytes.seek(0)
7
8
return func.HttpResponse(bdf_bytes.read(), mimetype="application/pdf")
9
10