[Python] Download Reportlab PDF only when the user clicks a button

Discussão em 'Python' iniciado por Stack, Abril 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to figure out how to only generate the PDF from Reportlab when the user clicks a Download button, instead of it automatically generating in my local folder. It is a streamlit application FYI.

    Here is the code I have to set up the PDF and memory.

    buffer = io.BytesIO()

    doc = canvas.Canvas(buffer, pagesize=letter)

    elements = []

    # Add simple text to PDF
    pdf_title = "Results"
    title_paragraph = Paragraph(pdf_title, getSampleStyleSheet()['Title'])

    # Add PDF title to PDF
    elements.append(title_paragraph)


    And here's the code I'm using to try to build the PDF and download it via a button. This is where I'm running into errors.

    doc.showPage()

    # Save the PDF
    doc.save()
    buffer.seek(0)

    def getpdf():
    response = HttpResponse(buffer, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="ClassificationResults"'.format("ClassificationResults.pdf")
    return response

    st.download_button("Download Results", downloadable_pdf, file_name='ClassificationResults', help=None, on_click="rerun",
    type="secondary", icon=None, disabled=False, use_container_width=False)


    I'm getting this error: RuntimeError: Invalid binary data format: <class 'django.http.response.HttpResponse'>

    So I believe the issue is with the getpdf() function but I got that code from another stack overflow example and I'm not sure how to troubleshoot. Any help would be greatly appreciated!

    Continue reading...

Compartilhe esta Página