View PDF on click of a button

I have to display a PDF onclick of a st.button. I’m calling that show_pdf function onclick of the button. The function is getting called but as the page is refreshing, the pdf disappears in second. I want to avoid the page refresh on Click of that button and display the pdf

Here is my code snippet:

def show_pdf(file_path, page_num):
with open(file_path,“rb”) as f:
base64_pdf = base64.b64encode(f.read()).decode(‘utf-8’)
pdf_display = f’’
st.markdown(pdf_display, unsafe_allow_html=True)

def load_answer(question,llm,document_count):
try:
similar_docs = docsearch.similarity_search(question, k=document_count)
for i in range(document_count):
st.write(similar_docs[i].page_content)
path = similar_docs[i].metadata[“source”]
page = similar_docs[i].metadata[“page”]
pdf_path = path
pdf_page = page
view_btn = st.button(‘View PDF’, on_click=show_pdf, args=(path,page), key={random.randint(1,99)})
llm_chain = load_qa_chain(llm, chain_type=“stuff”)
answer = llm_chain.run(input_documents=similar_docs,question=question)
consolidated = f"Final Summary - {answer}"
except Exception as e:
print(e)
consolidated = “Search Error: Reduce document count or search criteria”
return consolidated

Note: from load_answer() I’m callinf show_pdf()
pdf_page, pdf_path are global variables

Hey @Sobika,

Thanks for sharing your question!

Please update your post to format your code properly and share a link to your GitHub repo so we can reproduce the error (your code snippet isn’t runnable as-is).

You can use session state to store a variable that indicates whether the “display PDF” button has been clicked, and then display the PDF if that variable is true – that way, when your app reruns after someone interacts with a widget, the PDF will be displayed after the rerun.

1 Like

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