ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: HTML/CSS to PDF converter
Submitter: Dirk Holtwick (other recipes)
Last Updated: 2008/04/20
Version no: 1.0
Category: Web

 

4 stars 1 vote(s)


Description:

Most people know how to write a page with HTML and CSS. Why not using these skills to dynamically generate PDF documents using it? The open source project "pisa" http://www.htmltopdf.org enables you to to this quite simple in a pythonic way.

Source: Text Source

import cStringIO
import ho.pisa as pisa
import os

# Shortcut for dumping all logs on screen
pisa.showLogging()

def HTML2PDF(data, filename, open=False):

    """
    Simple test showing how to create a PDF file from
    PML Source String. Also shows errors and tries to start
    the resulting PDF
    """

    pdf = pisa.CreatePDF(
        cStringIO.StringIO(data),
        file(filename, "wb"))

    if open and (not pdf.err):
        os.startfile(str(filename))

    return not pdf.err

if __name__=="__main__":
    HTMLTEST = """
    <html><body>
    <p>Hello <strong style="color: #f00;">World</strong>
    <hr>
    <table border="1" style="background: #eee; padding: 0.5em;">
        <tr>
            <td>Amount</td>
            <td>Description</td>
            <td>Total</td>
        </tr>
        <tr>
            <td>1</td>
            <td>Good weather</td>
            <td>0 EUR</td>
        </tr>
        <tr style="font-weight: bold">
            <td colspan="2" align="right">Sum</td>
            <td>0 EUR</td>
        </tr>
    </table>
    </body></html>
    """

    HTML2PDF(HTMLTEST, "test.pdf", open=True)

Discussion:

For the conversion these third party modules are used: HTML5lib, Reportlab and TG CSS Parser. All components are written in pure Python to ensure platform independency. More Informations on http://www.htmltopdf.org

This approach is very useful for web applications. Examples for integration with WSGI, Django, Turbogears, CherryPy and simple CGI are provided.



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Wrapping template engine ...

4. Assignment in expression

5. SOLVING THE METACLASS ...

6. Povray for python

7. Calling Windows API ...

8. Generic filter logic ...

9. Function Decorators by ...

10. MS SQL Server log monitor




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.