Downloading String as .docx format with st.download_button

In my app, I use an LLM to generate a text response. I want to download it as a .docx file, but using the code below, my file is unreadable.

st.download_button("Download Cover Letter", data=cover_letter, file_name="cover_letter.docx")

I found the solution to this:

First, import python-docx - from docx import Document

def get_docx(text):
    document = Document()
    document.add_paragraph(text)
    bio = io.BytesIO()
    document.save(bio)
    return bio.getvalue()

And then:

st.download_button("Download Cover Letter", data=get_docx(cover_letter), file_name="cover_letter.docx", mime="docx")

I got this from:

  1. Downloading a MS Word document - #2 by gouravrana7
  2. save text to a docx file python - Stack Overflow
1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.