Use a plotly HTML result for Word templating

Hey,

I am trying to insert an image in a Word template using the WordFileImage object from the SDK.The image is the Plotly plot in HTML used in one of the WebView from the app. How can I convert the HTML content of my plot into a BinaryIO content that can be rendered into the template?
I tried the following code:

template_path = Path(__file__).parent.parent / 'templates/test.docx'
fig = go.Figure()
string_content = StringIO(fig.to_html())
binary_content = BytesIO(figure.read().encode('utf-8'))
components = []
components.append(WordFileImage(binary_content, 'image'))
with open(template_path, 'rb') as template:
    word_file = render_word_file(template, components)

1 Like

Hi,

I used the to_image function to first convert the plot to a png and then insert this in the WordFileImage

template_path = Path(__file__).parent.parent / 'templates/test.docx'
fig = go.Figure()
# fill figure
fig_bytes = fig.to_image(format='png')
binary_content = BytesIO(fig_bytes)
components = []
components.append(WordFileImage(binary_content, 'image'))
with open(template_path, 'rb') as template:
    word_file = render_word_file(template, components)
2 Likes

Thanks that worked! I just needed to add kaleido to the requirements.

Hi, wanted to add that it is also possible to write the image directly to a stream buffer or file.

template_path = Path(__file__).parent.parent / 'templates/test.docx'
fig = go.Figure()
# fill figure
stream_buffer = BytesIO()
fig.write_image(file=stream_buffer, format='png')
components = []
components.append(WordFileImage(stream_buffer, 'image'))
with open(template_path, 'rb') as template:
    word_file = render_word_file(template, components)
1 Like

Hi everyone,

how do you import plotly figure (from specific python script) in other python script (for word templating) ?

Best regards,
Louis

Hi Louis,

Your question is not clear, can you give an example what you would like to achieve with some code snippets.

Thanks,

Maarten

Hi @mweehuizen

I found my answer ! :slight_smile:

Than you