Streamlit应用中使用pdf.js Viewer嵌入PDF并实现指定页面跳转、文本高亮的问题求助
Streamlit应用中使用pdf.js Viewer嵌入PDF并实现指定页面跳转、文本高亮的问题求助
我正在开发一个Streamlit应用,需要在iframe中展示PDF,并且要实现以下三个功能:
- 打开PDF时直接跳转到可参数化的指定页面
- 打开PDF时自动高亮可参数化的指定文本/引用内容
- PDF在 viewer/iframe 里可以滚动浏览
基于这些需求,我没有选择streamlit-pdf-viewer自定义组件,而是尝试使用pdf.js来实现。
我把Streamlit应用精简成了最小版本的app.py,里面加了三个按钮/链接尝试实现需求,但都没成功:
import streamlit as st import streamlit.components.v1 as components import urllib def main(): st.title("Hello from streamlit-n-pdfjs!") # Locations of my (public) r2 bucket and the document in it I want to view BUCKET_URL = "https://pub-ec8aa50844b34a22a2e6132f8251f8b5.r2.dev" DOCUMENT_NAME = "FINAL_REPORT.pdf" # "Media stored in the folder ./static/ relative to the running app file is served at path app/static/[filename]" # ^ https://docs.streamlit.io/develop/concepts/configuration/serving-static-files local_pdfjs_path = "./app/static/pdfjs-4-9-155-dist/web/viewer.html" # Attempt to link to the doc using the pdf.js viewer PAGENUM = 100 HIGHLIGHT_QUOTE = 'exited the stage' ENCODED_QUOTE = urllib.parse.quote(HIGHLIGHT_QUOTE) FULL_DOC_URL = f"{BUCKET_URL}/{DOCUMENT_NAME}#page={PAGENUM}&search={ENCODED_QUOTE}" pdfjs_viewer = f"{local_pdfjs_path}?file={FULL_DOC_URL}" # Clicking the link below opens the correct pdf to the correct page, but does not search/highlight the quote text, # ...and of course does not open in an iframe st.markdown(f"[link to the doc I can't get to open in iframe w/ buttons below]({FULL_DOC_URL})") # opens doc in a new tab but doesn't search/highlight quote # clicking button below says "404: Not Found" if st.button("Show PDF in iframe with highlights, via pdfjs viewer"): components.iframe(pdfjs_viewer, height=800, scrolling=True) # Clicking the button below opens an iframe border, but # just says "this page has been blocked by chrome" inside if st.button("Show PDF in iframe with highlights, via regular url w/ encoded params"): components.iframe(FULL_DOC_URL, height=800, scrolling=True) if __name__ == "__main__": main()
我的项目结构如下,已经将最新版的pdf.js解压后放到vendor/目录下:
streamlit_n_pdfjs |--app.py |--vendor |----pdfjs-4-9-155-dist |------web |--------viewer.html
另外,为了支持静态文件服务,我配置了.streamlit/config.toml:
[server] enableStaticServing = true
启动应用的命令是:
PYTHONPATH=. streamlit run app.py
现在三个按钮/链接的问题分别是(附应用截图):
- 第一个普通链接:点击后在新标签页打开PDF,能跳转到指定页面,但不会高亮目标文本,而且不是在iframe中打开(这个主要是用来测试PDF的URL是否可用)
- 第二个按钮:点击后iframe中显示“404: Not Found”,无法加载pdf.js viewer和PDF
- 第三个按钮:点击后只显示iframe边框,内部提示“this page has been blocked by chrome”,加载失败
我现在卡在这里了,不知道怎么调整才能让pdf.js在Streamlit的iframe中正常工作,同时实现指定页面跳转和文本高亮的功能,有没有大佬能帮忙分析下问题出在哪?
备注:内容来源于stack exchange,提问作者Max Power
相关产品推荐
相关产品推荐

