wkhtmltopdf create PDF from html

  1. clean the html content

    remove some string tag, some section of html not need for pdf

    replace the static file path to local file path

    example: rendered_html = final_html.replace(f'{base_url}static’, f’file:///{app_root}/static’)

  2. wkhtmlpdf executable path and configuration

    “use pdfkit for support “

    path_wkhtmlpdf = f'{BASE_DIR}\wkhtmltopdf\bin\wkhtmltopdf.exe’
    pdf_config = pdfkit.configuration(wkhtmltopdf=path_html_to_pdf)

    “pdf configurations”

    options = {

         'page-size': 'Letter',
         'margin-top': '0.5in',
         'margin-bottom': '0.5in',
         'margin-right': '0.15in',
         'margin-left': '0.15in',
         'dpi': 300,
         'header-center': f'{header_txt}',
         'custom-header': [('Accept-Encoding', 'gzip')],
         'header-line': '',
         'header-font-size': 9,
         'header-spacing': 4,
         'footer-right': 'Page [page] of [topage]',
         'footer-center': f'Copyright © {datetime.datetime.now().year}',
         'footer-font-size': 6,
         'footer-line': '',
         'footer-spacing': 4,
         'encoding': "utf-8",
         'no-outline': None,
         'javascript-delay': 600,
         'enable-local-file-access': '',
         'quiet': '',
         'print-media-type': ''
     }
    
     pdfkit.from_string(rendered_html_pdf, pdf_file, configuration=to_pdf_config, options=options,
                        css=f'{BASE_DIR}\\static\\css\\pdf.css')
     
     and put some css configuration for pdf in this pdf.css
    

see more from wkhtmlpdf website.