Home > Software design >  Return PDF in Azure Function via HttpResponse (PyPDF2)
Return PDF in Azure Function via HttpResponse (PyPDF2)

Time:06-06

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:

import logging

import azure.functions as func
from PyPDF2 import PdfFileReader, PdfFileWriter


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('----- Python HTTP trigger function processed a request. -----')

    BLOB_NAME = 'sheet.pdf'

    reader = PdfFileReader(BLOB_NAME)
    writer = PdfFileWriter()

    page = reader.pages[0]

    writer.addPage(page)

    sheetData = {}
    sheetData["Full Name"] = "Name"

    writer.updatePageFormFieldValues(writer.getPage(0), sheetData)

    return func.HttpResponse(writer, mimetype="application/pdf")

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.

CodePudding user response:

Try creating a bytes object to return:

import io

pdf_bytes = io.BytesIO()

writer.write(pdf_bytes)
pdf_bytes.seek(0)

return func.HttpResponse(bdf_bytes.read(), mimetype="application/pdf")

  • Related