PDF Generation through Streamlit Sharing Cloud (HTML to PDF)

Summary

I have created a pump selection app in Streamlit and the app Works Perfect in terms of calculation and everything else. But when I get to the part where I need to generate a PDF document based on an HTML string I get an error indicating that the wkhtmltopdf cannot be found.

Steps to reproduce

Code snippet:

import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import pdfkit
import base64
import os 

#RESULTS SECTION 
# Path to wkhtmltopdf binary
wkhtmltopdf_path = os.path.join(os.getcwd(), 'wkhtmltopdf', 'bin', 'wkhtmltopdf')
if not os.path.isfile(wkhtmltopdf_path):
    raise FileNotFoundError("wkhtmltopdf executable not found at %s" % wkhtmltopdf_path)
# Configure pdfkit to use the binary
config = pdfkit.configuration(wkhtmltopdf=wkhtmltopdf_path)
st.markdown("---")
st.subheader('Print Results')
# prompt the user to enter a filename
filename = st.text_input("Enter a filename for the PDF file:", f"{selected_pump} Duty point")
# add the .pdf extension to the filename
filename = filename.strip() + ".pdf"
if st.button("Generate PDF"):
    # generate the PDF file as a bytes object
    pdfkit.from_file(input_path, output_path, configuration=config)
    # download the PDF file
    if pdf_bytes is not None:
        st.success("PDF file Generated. Click on 'Download PDF' to save.")
        b64 = base64.b64encode(pdf_bytes).decode()
        href = f'<a href="data:application/pdf;base64,{b64}" download="{filename}">Download PDF file</a>'
        st.markdown(href, unsafe_allow_html=True)
        # remove the success message and download link
        st.empty()
    else:
        st.warning("PDF file generation failed. Please try again.")

Expected behavior:

I expect a PDF to be generated in bytes object that can then be transformed into a PDF that the user can download

Actual behavior:

the program is not finding the wkhtmltopdf executable file, but Github does not let me upload it since it weighs more than 25 megabytes

Requirements file

streamlit
pandas
numpy
matplotlib
scipy
pdfkit
importlib_resources
openpyxl
weasyprint
cairocffi
cffi
Pillow

You can list that package in the packages.txt file to get it installed in Cloud Community. Check App dependencies - Streamlit Docs for details.

That should also take care of having to set the exact path to the wkhtmltopdf executable.

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