string html to pdf in python using pdfkit wkhtmltopdf

Skip to first unread message

Kailash Chandra

Jan 3, 2024, 6:07:16 AMJan 3
to wkhtmltopdf General

I want to generate a pdf with header.html, footer.html and options. in windows it's working fine but when I m working on ubuntu pdf is created with content but header and footer is not rendering and page options is also not working.

I request to you please give me some solutions. I m sending my code also.

def pdf_generate_and_download(html_content, unique_key):
    pdf_options = {
        'enable-local-file-access': None,
        'page-size': 'A4',
        'margin-top': '0.74in',
        'margin-left': '0in',
        'margin-right': '0in',
        'margin-bottom': '0.79in',
        'footer-spacing': '5',
        'footer-font-size': '10',
        'footer-font-name': 'sans-serif',
        'encoding': 'UTF-8',
        'header-html': 'templates/terms_pdf_header.html',
        'footer-html': 'templates/terms_pdf_footer.html',
        'header-spacing': '5',  # 1 * 4 = header-spacing
        'title': 'Pdf Title',
        'no-outline': None

    pdf_path = f'{unique_key}.pdf'
    tuple_of_path = subprocess.getstatusoutput('which wkhtmltopdf')
    if tuple_of_path[0] == 0:
        path_wkhtmltopdf = tuple_of_path[1]
        logger.error({"message": "wkhtmltopdf not setup."})
        raise CustomAPIException(400, detail="wkhtmltopdf not setup.")

    # path_wkhtmltopdf = r"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"
    config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf)

    # pdfkit.from_string(html_content, pdf_path, configuration=config, options={"enable-local-file-access": ""})
    pdfkit.from_string(html_content, pdf_path, configuration=config, options=pdf_options)
    if os.path.exists(pdf_path):
        with open(pdf_path, 'rb') as pdf_file:
            response = HttpResponse(pdf_file, content_type='application/pdf')
            response['Content-Disposition'] = f'attachment; filename={pdf_path}'

            # removed generated pdf.
            return response

    raise Http404

Thank you
Reply all
Reply to author
0 new messages