Include an existing html file in Streamlit app

Hi community,

I am looking to include some existing Plotly figures that were saved as html objects (fig.write_html()) in my Streamlit app.

Is there a way I can do this?

And in general is there a way to include html chunks in the app?

Edit: I tried the streamlit components, which works with pages on the web

import streamlit.components.v1 as components
components.iframe("https://docs.streamlit.io/en/latest")
components.iframe("https://www.randomservices.org/")

but not for local pages

components.iframe("path/to/page.html")

in which case the app displays

404: Not Found

Where should the pages be placed?

2 Likes

Hi @Pill, welcome to the Streamlit community!

You were closeโ€ฆyou can use components.html to add HTML to a page. You need to read the HTML into a Python string using the file open functionality, then pass that string to components.html.

3 Likes

Hi @randyzwitch,

Thank you for the pointer! components.html works.

Hereโ€™s a minimal reproducible exmple:

import streamlit as st
import streamlit.components.v1 as components

# >>> import plotly.express as px
# >>> fig = px.box(range(10))
# >>> fig.write_html('test.html')

st.header("test html import")

HtmlFile = open("test.html", 'r', encoding='utf-8')
source_code = HtmlFile.read() 
print(source_code)
components.html(source_code)

where the html file is generated with the code commented out.

However, the html height is defaulted to 150 pixels. Is there a way to make the height adaptive to the input html?

Thank you!

4 Likes

Not at the moment, but itโ€™s a highly requested feature!

If you have a rough idea of what you expect, you can set the attributes inside of components.html(..., height = 600). Youโ€™re reading in HTML directly, but frequently if youโ€™re starting with a Python graph of some kind, you can read the height from the Python object directly which mimics the behavior you are talking about.

Thank you!
Streamlit has been a great tool. Looking forward to future updates!

what we have to do if we want that html page to open in a new tab on clicking a button

1 Like

If that javascript in that html generates a json string,how can i get it in streamlit python?

To communicate from the browser back to Python/Streamlit, you need to write a bi-directional component:

https://docs.streamlit.io/en/stable/develop_streamlit_components.html#create-a-bi-directional-component

How can we disply an engineering drawing from visio as example