streamlit・gradioでpdf ファイルを表示させる


streamli・gradioで、pdfファイルをアップロードして中身を表示させる方法を試してみた。どちらも案外かんたんにできた

streamlit

2025-10-16更新

公式のカスタムコンポーネントきてた。st.pdf

こちらでサンプルのappを公開した。画面からコード見れないのでコードも貼っておく https://st-apps-drksd2n53geuc486rf4nbw.streamlit.app/

こんな感じズームできて便利ー

st-pdf-viewer

以下のパッケージをインストールする必要があるので注意

pip install 'streamlit[pdf]'
import streamlit as st
 
def upload_pdf_file():
    uploaded_file = st.file_uploader("Upload PDF file", type="pdf")
 
    return uploaded_file
 
def display_pdf(uploaded_file):
    if uploaded_file is not None:
        pdf_contents = uploaded_file.read()
        st.pdf(pdf_contents, height="stretch")
 
def main():
    st.title("pdf viewer")
    file = upload_pdf_file()
 
    if file is not None:
        display_pdf(file)
 
main()

ref.

引数にURLを直接指定できるが、corsエラーなどが起きたので、旧記述どおりにfile uploadする方式にした

2025-10-16以前

htmlのembedタグでpdfデータを埋め込む

import streamlit as st
import base64
import os
 
def upload_pdf_file():
    uploaded_file = st.file_uploader("Upload PDF file", type="pdf")
    if uploaded_file is None:
        st.write("Please upload a PDF file.")
    return uploaded_file
 
def display_pdf(uploaded_file):
    if uploaded_file is not None:
        pdf_contents = uploaded_file.read()
        pdf_base64 = base64.b64encode(pdf_contents).decode('utf-8')
        encoded_pdf = f'<embed src="data:application/pdf;base64,{pdf_base64}" width="800" height="600" type="application/pdf">'
        st.markdown(encoded_pdf, unsafe_allow_html=True)
 
    else:
        st.write("No PDF file uploaded.")
        st.write(pdf_contents, unsafe_allow_html=True)
 
def main():
    file = upload_pdf_file()
 
    if file is not None:
        display_pdf(file)
 
main()
 

firefoxで動作した。chromeだとpdfの表示ができなかった

st-viewer

作成したstreamlit app

https://st-apps-drksd2n53geuc486rf4nbw.streamlit.app/

試していないが、こちらのカスタムコンポーネントを使うのでもよさそう

https://github.com/lfoppiano/streamlit-pdf-viewer

gradio

こちらはカスタムコンポーネントを用いた

import gradio as gr
from gradio_pdf import PDF
 
with gr.Blocks() as app:
    gr.Markdown("# PDF viewer\n")
    with gr.Row():
        pdf = PDF(label="Document")
 
app.launch()
pip install gradio_pdf

gr-viewer

作成したgradio app

https://huggingface.co/spaces/uni3/pdf-viewer

参考