Comprehensive Guide on WeasyPrint Turning HTML and CSS into PDFs Seamlessly

Introduction to WeasyPrint

WeasyPrint is a powerful, open-source tool that allows developers to effortlessly convert HTML and CSS documents into high-quality PDF files. It is built using Python and is extremely versatile, making it ideal for automating document generation tasks in various applications. If you’re looking for a robust solution to handle document formatting, WeasyPrint is an all-in-one PDF generation tool worth considering.

Why Choose WeasyPrint?

WeasyPrint is versatile and easy to use, providing developers with full control over the layout of their documents. By leveraging common knowledge of HTML and CSS, you can craft visually stunning, well-structured documents that comply with styling norms. Whether it is for invoices, reports, certificates, or dynamic printing needs, WeasyPrint simplifies the process, saving time and effort.

Getting Started with WeasyPrint

  # Install WeasyPrint with pip
  pip install weasyprint

Once installed, you can convert HTML and CSS files into PDFs with just a few lines of code.

Basic Usage Example

  from weasyprint import HTML

  # Convert an HTML file to PDF
  HTML('example.html').write_pdf('output.pdf')

Adding Custom Styles

WeasyPrint allows you to apply custom CSS styles to your documents.

  HTML(string='<h1>Hello, World!</h1>', base_url='.').write_pdf(
      'styled.pdf',
      stylesheets=['styles.css']
  )

Using Multiple Stylesheets

  HTML(string='<h1>Styled Document</h1>').write_pdf(
      'multi_style.pdf', 
      stylesheets=['base.css', 'theme.css']
  )

Creating PDFs from URLs

  HTML('https://example.com').write_pdf('website_output.pdf')

Adding Metadata

Embed metadata in your document using WeasyPrint options.

  HTML(string="<h1>Document</h1>").write_pdf(
      'metadata.pdf',
      presentational_hints=False,
      optimize_size=True
  )

Advanced Usage of WeasyPrint

Generating Reports Dynamically

Using WeasyPrint, you can create dynamic content by combining it with templating engines such as Jinja2.

  from jinja2 import Template
  from weasyprint import HTML

  # Define an HTML template
  template_string = '''
  <html>
    <body>
      <h1>Customer Report</h1>
      <p>Customer Name: {{ customer_name }}</p>
    </body>
  </html>
  '''
  template = Template(template_string)

  # Pass data to the template
  html_content = template.render(customer_name='John Doe')
  HTML(string=html_content).write_pdf('report.pdf')

Handling Large Documents

Effortlessly manage and generate large PDF files using WeasyPrint.

  content = '<h1>Large Document</h1>' + '<p>Page Content</p>' * 500
  HTML(string=content).write_pdf('large_output.pdf')

Example: Building an Invoice Generator App

Below is an example of how you can use WeasyPrint to create an invoice generator app:

  from jinja2 import Template
  from weasyprint import HTML
  import os

  # Define an invoice template
  template_string = '''
  <html>
    <body>
      <h1>Invoice</h1>
      <table>
        <tr>
          <th>Item</th>
          <th>Price</th>
        </tr>
        {% for item, price in invoice_items %}
        <tr>
          <td>{{ item }}</td>
          <td>${{ price }}</td>
        </tr>
        {% endfor %}
      </table>
    </body>
  </html>
  '''
  template = Template(template_string)

  # Substitute invoice data
  invoice_items = [('Product 1', 10), ('Product 2', 20)]
  html_content = template.render(invoice_items=invoice_items)

  # Convert to PDF
  output_file = os.path.join('invoices', 'invoice_001.pdf')
  HTML(string=html_content).write_pdf(output_file)

This example demonstrates how easily you can integrate WeasyPrint into a Python application to generate professional PDF documents automatically.

Final Thoughts

WeasyPrint is a feature-rich library that simplifies the process of creating PDF documents from HTML and CSS, while offering myriad customization options. With its ease of use, flexibility, and powerful features, it is an essential tool for developers working with document generation tasks.

Leave a Reply

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