Need help with "Error Failed to load PDF document"

I am uploading a pdf file in the sql database, but when I am displaying or downloading it after extracting from the database I am getting “Failed to load PDF document.”

Here is my code snippet to upload pdf

uploaded_paper = st.file_uploader('Upload your research paper', type=['pdf'])
research_paper = uploaded_paper.read()
nsert_query = "INSERT INTO DOCUMENTS (doc, title_of_doc, authors, publisher, date_of_publication, keyword, empID) VALUES (%s, %s, %s, %s, %s, %s, %s)"
insert_tuple = (research_paper, str(title_of_doc), str(authors), str(publisher), str(date_of_publication), str(keywords), str(empID))
        
   try:
       cursor.execute(insert_query, insert_tuple)
       connection.commit()
       cursor.nextset()  # Move to the next result set to skip any unread result
       cursor.close()
       connection.close()
   except Error as e:
       st.error(f"Error occurred: {e}")
       st.error(f"Error details: {cursor._executed}")

And here is my code snippet to view and download pdf

            base64_pdf = base64.b64encode(doc).decode('utf-8')
            pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="620" height="150" type="application/pdf"></iframe>'
            st.markdown(pdf_display, unsafe_allow_html=True)

            download_filename = f"{title_of_doc}.pdf"
            count = random.randint(1,10000000)
            st.download_button("Download the paper", data=doc, file_name=download_filename, mime='application/octet-stream', key=count)

The doc type in SQL database is mediumblob. I don’t know what is the error in my code and how to solve this. Please help!

I think some code is truncated… nsert_query... and I’m not seeing how your final pdf (doc) is being acquired so I’m not sure what to say. A few things to consider or test:

  1. Try just uploading and displaying a pdf without the extra query code in between.
  2. I believe Chrome and Edge are more likely to have issues displaying pdfs vs FireFox for example. They may be some details with security settings or some internal formatting of the pdf that can matter. So try different browsers and try different pdf files.
  3. Try downloading whatever your resultant pdf is and opening it locally to confirm you are getting a valid pdf format.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.