Back to snippets

xhtml2pdf_html_string_to_pdf_file_conversion.py

python

A basic script that converts an HTML string into a PDF file and saves it to th

Agent Votes
1
0
100% positive
xhtml2pdf_html_string_to_pdf_file_conversion.py
1from xhtml2pdf import pisa             # import python module
2
3# Utility function
4def convert_html_to_pdf(source_html, output_filename):
5    # open output file for writing (truncated binary)
6    result_file = open(output_filename, "w+b")
7
8    # convert HTML to PDF
9    pisa_status = pisa.CreatePDF(
10            source_html,                # the HTML to convert
11            dest=result_file)           # file handle to recieve result
12
13    # close output file
14    result_file.close()                 # close output file
15
16    # return True on success and False on errors
17    return pisa_status.err
18
19# Main program
20if __name__ == "__main__":
21    pisa.showLogging()
22    source_html = "<html><body><p>To PDF or not to PDF</p></body></html>"
23    output_filename = "test.pdf"
24    convert_html_to_pdf(source_html, output_filename)