Comprehensive Guide to Xhtml2pdf for Generating PDFs in Python

Introduction to Xhtml2pdf

Xhtml2pdf is a Python library that allows developers to create, convert, and manipulate PDF documents from HTML and CSS content. It is particularly useful for generating PDF reports, invoices, and other documents dynamically in web applications. With Xhtml2pdf, you can harness the power of familiar web technologies like HTML and CSS to design and style your PDF documents with ease.

Getting Started with Xhtml2pdf

To use Xhtml2pdf, you first need to install it via pip:

  pip install xhtml2pdf

Basic Usage

Here’s a simple example of converting HTML content to a PDF document:

  from xhtml2pdf import pisa

  # Function to convert HTML to PDF
  def convert_html_to_pdf(source_html, output_filename):
      with open(output_filename, "wb") as result_file:
          pisa_status = pisa.CreatePDF(source_html, dest=result_file)
      if pisa_status.err:
          print("Error during conversion")
      else:
          print(f"PDF successfully created: {output_filename}")

  # Sample HTML content
  html_content = """
  
      
          
      
      
          

Hello, Xhtml2pdf!

This is a sample PDF generated using Xhtml2pdf.

""" # Convert the HTML content to a PDF convert_html_to_pdf(html_content, "output.pdf")

Working with Templates

You can also use HTML templates to generate dynamic content:

  from jinja2 import Template
  from xhtml2pdf import pisa

  # HTML template with placeholders
  html_template = """
  
      
          

Invoice

Customer Name: {{ customer_name }}

Amount Due: ${{ amount_due }}

""" # Rendering the template with data def generate_invoice(data, output_filename): template = Template(html_template) html_content = template.render(data) with open(output_filename, "wb") as result_file: pisa_status = pisa.CreatePDF(html_content, dest=result_file) if not pisa_status.err: print(f"Invoice generated successfully: {output_filename}") # Example usage invoice_data = { "customer_name": "John Doe", "amount_due": 150.75 } generate_invoice(invoice_data, "invoice.pdf")

Adding Images to PDF

Including images in your PDF is straightforward:

  html_content = """
  
      
          

PDF with Images

Sample Image """ convert_html_to_pdf(html_content, "pdf_with_images.pdf")

Highlighting Dozens of Useful APIs

Xhtml2pdf comes with several methods and options to customize your PDFs. Here are some notable functionalities:

  • Supporting CSS for advanced styling.
  • Adding headers and footers using HTML and CSS.
  • Embedding fonts in PDF documents for improved readability.
  • Handling tables and other complex layouts.
  • Support for external CSS stylesheets and inline styles.

Example with Styling

You can use inline CSS or link external stylesheets for better control over the PDF content:

  html_content = """
  
      
          
      
      
          

Styled PDF Example

This PDF uses an external stylesheet for styling.

""" convert_html_to_pdf(html_content, "styled_example.pdf")

Example Web Application Using Flask and Xhtml2pdf

Let’s build a basic Flask web app that generates a PDF dynamically:

  from flask import Flask, render_template, request, make_response
  from xhtml2pdf import pisa

  app = Flask(__name__)

  @app.route("/")
  def index():
      return """
      
""" @app.route("/generate", methods=["POST"]) def generate_pdf(): name = request.form.get("name") html_content = f"""

Welcome, {name}!

This is your personalized PDF.

""" response = make_response() result = pisa.CreatePDF(html_content, dest=response) if not result.err: response.headers["Content-Type"] = "application/pdf" response.headers["Content-Disposition"] = "inline; filename=output.pdf" else: response = f"Error during PDF generation" return response if __name__ == "__main__": app.run(debug=True)

Conclusion

Xhtml2pdf is a powerful library for generating high-quality PDFs in Python using HTML and CSS. Whether you’re working on automated invoice generation or dynamic PDF reports, Xhtml2pdf makes the process efficient and straightforward. With these examples and tips, you’re ready to start building robust PDF functionalities in your Python projects.

Leave a Reply

Your email address will not be published. Required fields are marked *