Using a plotly express "fig" in a python-pptx slide as an image

What I’m trying to do:
I am creating bar graphs in a server module using plotly express. The end result is a plotly express ‘figure.’ I need to pass that to my python-pptx code that is creating PowerPoints slides where I want to display the result graph as an image, in a picture on my slide(s). I need to convert that “fig” to an actual files, I know I can use fig.write_to_file(“path/filename.jpg”) to get my image file, however, my first stab at this is returning a read-only file system error and, not sure I want to write to the file system and then have to retrieve it in my python-pptx code.

Is there a way to use plotly express to create that image file and stuff it into an object I can pass to my python-pptx code?

Figured it out, here for reference:

In the server module, using plotly express, the resulting object is a plotly-express figure “fig”

Then this code will render that into a media object:

  graph = fig.to_image()

  file = anvil.BlobMedia(content_type="bytes", content=graph) 

  return file

I return that, and then in the front end, simply set the image.source to that returned object

UPDATE: Ah crap… so this works in my test… but not in python-pptx… that is still requiring a file and I don’t have a file

You have a media object, and can get a file from that: Anvil Docs | Files, Media Objects and Binary Data at least a file name of a file that contains the contents of the media file.

1 Like

Found it, this works

    file = app_tables.images.search(name='powered_by_xxxxxx')[0]['file']
    with anvil.media.TempFile(file) as img_file:
      slide.shapes.add_picture(img_file, Inches(8.2), Inches(7.05), width=Inches(1.5), height=Inches(.25))