I want to download a PDF that includes the content of tab 4 in my Dash application. It’s important that the visual content (front end) is preserved. With my current script, I managed to export a PDF, but it only contains text and doesn’t display the charts and cards as I intended.
app.layout = html.Div(
[
html.Div(
[
html.Img(src='/assets/ESCUDO_EDLP.png', style={'height': '95px', 'width': '60px', 'margin-bottom': '20px'}),
html.H1("DASHBOARD NUTRICIÓN ESTUDIANTES DE LA PLATA",
style={'text-align': 'center', 'font-size': '30px', 'margin-bottom': '20px', 'color': 'white'}),
],
style={'display': 'flex', 'flex-direction': 'column', 'align-items': 'center', 'background-color': 'black',
'padding': '10px'}
),
dbc.Tabs(
[
dbc.Tab(tab1_content, label="INFORME EVOLUTIVO INDIVIDUAL",
label_style={'color': 'black', 'background-color': 'white'},
active_label_style={'color': 'red'}),
dbc.Tab(tab2_content, label="DASH DE GESTIÓN",
label_style={'color': 'black', 'background-color': 'white'},
active_label_style={'color': 'red'}),
dbc.Tab(tab3_content, label="INFORME COLECTIVO",
label_style={'color': 'black', 'background-color': 'white'},
active_label_style={'color': 'red'}),
dbc.Tab(tab4_content, label="INFORME INDIVIDUAL",
label_style={'color': 'black', 'background-color': 'white'},
active_label_style={'color': 'red'}),
dbc.Tab(label="CARGA DE DATOS",
label_style={'color': 'black', 'background-color': 'white'},
active_label_style={'color': 'red'},
)
],
id="tabs",
),
html.Button('Descargar PDF', id='btn-download-pdf', n_clicks=0),
dcc.Download(id='download-pdf')
],
style={'position': 'relative'}
)
@app.callback(
Output('download-pdf', 'data'),
Input('btn-download-pdf', 'n_clicks'),
State('tab-4', 'children')
)
def download_pdf(n_clicks, tab4_children):
if n_clicks > 0:
# Convertir el contenido HTML de la pestaña 4 a una cadena
html_content = str(tab4_children)
# Crear un archivo temporal para almacenar el HTML
with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as temp_file:
temp_file.write(html_content.encode("utf-8"))
# Generar el PDF a partir del archivo temporal HTML
output_file = "informe_individual.pdf"
options = {'disable-local-file-access': True}
pdfkit.from_file(temp_file.name, output_file, configuration=pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'), options=options)
# Leer el contenido del archivo PDF generado
with open(output_file, "rb") as pdf:
pdf_data = pdf.read()
# Crear un diccionario con los datos del PDF para su descarga
return dcc.send_bytes(pdf_data, filename=output_file)
return None