python flask create PDF page

  1. render the html page with flask render_template()
  2. pass( using flask session) the rendered html content to pdf function
  3. using pdfkit(https://pypi.org/project/pdfkit/), together with wkhtmltopdf package(https://wkhtmltopdf.org/) to convert the html to pdf and save to local, then flask send to download

    –before the convert, you can modify the html content for export, like remove something don’t want to see in PDF

    some code section:

       path_of_wkhtmltopdf=r'c:\temp\wkhtmltopdf\bin\wkhtmltopdf.exe'
       pdfkit_config= pdfkit.configuration(wkhtmltopdf=path_of_wkhtmltopdf)
       # some page configuration
       options ={
                 'page-size':'letter',
                  'header-center':f'{header}',
                   'footer-center':f'{footer_txt}',
                    .....
                    }
       pdf_result=r'c:\temp\pdfoutput\test.pdf'
       pdfkit.from_string(final_html, pdf_file, configuration=pdfkit_config, options=options)
       return send_file(pdf_file, as_attachment=True)
    

with this you can create PDF file from the page on the fly, or user clicks.