0

I am storing PDF documents in MongoDB; base64 encoded. I want to serve these PDFs from a view function. I'm hoping to eventually embed them into an HTML embed element or Iframe. For now, I'm just trying to get this to work.

Similar questions:

Here is my view:

def pdf(request, pdf_id):    
    document = mongo_db_client.get_document(pdf_id) # uses a find_one query, returns a cursor on the document
    pdf = base64.b64decode(document.read())
    print(f"pdf type: {type(pdf)}")
    print(f"pdf length: {len(pdf)}")

    # We save the PDF to the filesystem to check 
    # That at least that works:
    with open("loaded_pdf.pdf", "wb") as f:
        f.write(pdf) 

    # See: https://docs.djangoproject.com/en/4.0/howto/outputting-pdf/
    _buffer = io.BytesIO(pdf)
    p = canvas.Canvas(_buffer)
    p.showPage()
    p.save()
    _buffer.seek(0)

    return FileResponse(_buffer, content_type='application/pdf')

The output of this is that I am able to view the PDF saved to the filesystem and the print output is:

pdf type: <class 'bytes'>
pdf length: 669764

Now, for one of the PDFs that I have, I can open the URL and view it in the browser. For another PDF that I have, it fails to load in the browser, showing only the PDF title. In both cases, the PDF saved to the filesystem and I can view it there without error.

Any ideas?

Neil
  • 2,505
  • 3
  • 16
  • 37

0 Answers0