Download file with dcc.send_bytes

Question:

I am trying to create and download a pptx presentation with pptx and python dash. Although the file is created without an error, there are no slides created in the presentation.

Thanks in advance.

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
from dash.dependencies import Input, Output

from pptx import Presentation
import io

app = dash.Dash(__name__,external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = html.Div([html.Button('Download Slides', id='download_button', n_clicks=0), dcc.Download(id='download')])

@app.callback(Output('download', 'data'), [Input('download_button', 'n_clicks')])
def download_file(n_clicks):
    if n_clicks == 0:
        raise PreventUpdate
    
    def to_pptx(bytes_io):
    
        prs = Presentation()
        title_slide_layout = prs.slide_layouts[0]
        slide = prs.slides.add_slide(title_slide_layout)
        title = slide.shapes.title            
        title.text = 'Hello, World!'

        filename = io.BytesIO() #io.StringIO()
        prs.save(filename)            
        filename.seek(0)

    return dcc.send_bytes(to_pptx, 'Slides.pptx')

if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=False)
Asked By: dsforecast

||

Answers:

You can use this code instead:

def to_pptx(bytes_io):
    prs = Presentation()
    title_slide_layout = prs.slide_layouts[0]
    slide = prs.slides.add_slide(title_slide_layout)
    title = slide.shapes.title
    subtitle = slide.placeholders[1]    
    title.text = "Hello, World!"
    subtitle.text = "python-pptx was here!"    
    prs.save(bytes_io) #<------ save the file this way

return dcc.send_bytes(to_pptx, 'Slides.pptx')
Answered By: Hamzah
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.