Search code examples
pythonpython-3.xpdfmarkdownstreamlit

How to convert and download markdown text as a pdf report in Streamlit?


I have markdown text generated in Streamlit as below.

st_md = '''
<b>compare mongodb to other no sql databases</b><br><br><b>Uploaded Files: </b>[]<br><br> Here is a comparison of MongoDB to some other major NoSQL databases:

- MongoDB is a document database. It stores data in flexible JSON-like documents rather than rows and columns like an RDBMS. Other document databases include CouchDB and Amazon DocumentDB.


In summary, MongoDB strikes a balance between the flexibility of document storage, rich functionality like secondary indexes and aggregations, and scalability via horizontal sharding that makes it a popular choice among many NoSQL databases today.<br><br><b>advantages and disadvantages of mongodb to other no sql ds</b><br><br><b>Uploaded Files: </b>[]<br><br> Here are some key advantages and disadvantages of MongoDB compared to other NoSQL databases:

Advantages:

- Flexible data model using documents to represent objects with dynamic schemas. More flexible than columnar databases that require predefined schemas.

- Index on any attribute for faster queries and retrieval compared to key-value stores.


Disadvantages:

- Less ACID compliance and transactions than traditional SQL databases.

- No declarative query language like SQL. Query syntax can be complex for some use cases.

So in summary, MongoDB provides a flexible document data model with rich functionality leading to faster reads and more expressiveness compared to simple key-value stores, but lacks some features database specialists may require. Scaling and performance is generally easier than traditional SQL databases.<br><br>
'''

I would like to download the content of st_md into a pdf file. I tried using the download_button but receive an error that the pdf file is damaged. What am I missing?

st.download_button(
    label="Download data as pdf",
    data=st_md,
    file_name='test.pdf',
)

Solution

  • Using the suggestion from @Chathura Abeywickrama, I converted my markdown content to pdf using the below:

    html = markdown2.markdown(st_md)
    pdfkit.from_string(html, 'example.pdf')
    

    Then use the generated pdf file in download_button

    with open("example.pdf", "rb") as f:
        st.download_button("Download Conversation", f, f"example.pdf")