xhtml2pdf

0.2.17 · active · verified Fri Apr 10

xhtml2pdf is an active Python library that converts HTML and CSS into PDF documents, leveraging the ReportLab Toolkit, html5lib, and pypdf. It supports HTML5 and CSS 2.1 (with some CSS 3), offering a platform-independent solution for generating PDFs from web content. The project maintains a regular release cadence, with the current version being 0.2.17.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to convert an HTML string into a PDF file using `pisa.CreatePDF`. The function takes the HTML content and a file handle (opened in binary write mode) as arguments. It then saves the generated PDF to the specified output file.

from io import BytesIO
from xhtml2pdf import pisa

html_content = '''
<html>
  <head>
    <style>
      @page { size: A4 portrait; margin: 1cm; }
      h1 { color: #333; }
      p { font-family: sans-serif; }
    </style>
  </head>
  <body>
    <h1>Hello from xhtml2pdf!</h1>
    <p>This is a simple HTML to PDF conversion example.</p>
    <p>Visit <a href="https://github.com/xhtml2pdf/xhtml2pdf">xhtml2pdf on GitHub</a>.</p>
  </body>
</html>
'''

def convert_html_to_pdf(source_html, output_filename):
    result_file = open(output_filename, 'w+b') # Open in binary write mode
    pisa_status = pisa.CreatePDF(
        source_html,    # the HTML to convert
        dest=result_file)  # file handle to receive result
    result_file.close()    # close output file

    if pisa_status.err:
        print(f"PDF creation failed with errors: {pisa_status.err}")
        return False
    else:
        print(f"PDF created successfully: {output_filename}")
        return True

# Example usage:
convert_html_to_pdf(html_content, "example.pdf")

view raw JSON →