Send pdf from pikepdf as BytesIO stream - flask send_file content length mismatch

1.1k views Asked by At

I am trying to send a pdf as an api response using Flask. However, I get a ERR_CONTENT_LENGTH_MISMATCH on the client side of the api. Maybe this is caused by the stream not being complete while the file is send to the client? Idk

from flask import Flask, send_file, make_response

app = Flask(__name__)

@app.route("/")
def get_pdf(request):
    # Set CORS headers for the preflight request
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)

    pdf = Pdf.open('test.pdf')
    file = io.BytesIO()
    pdf.save(file)

    response = make_response(send_file(file, download_name="project_pdf", mimetype='application/pdf', as_attachment=True))
    response.headers.set('Access-Control-Allow-Origin', '*')

    return response
0

There are 0 answers