Submit Blog  RSS Feeds

Thursday, April 26, 2012

Convert HTML/CSS to PDF (preserving layout) using python pisa

A few days ago I published a post regarding PDF file  generation. I mentioned that I may be able to say a few words about positioning elements using pisa at-keywords. The first thing you should know, is that although CSS is suppose to be supported, most positioning properties won't work... until you apply them inside an appropriate block. Take a look at this head section:

  1 <head>
  2     <style type="text/css">
  3        @page {
  4             size: a4;
  5             @frame {
  6                 -pdf-frame-content: "footer";
  7                 top: 25.8cm;
  8                 margin-right: 2.8cm;
  9                 margin-left: 2.8cm;
 10             }   
 11             @frame {
 12                -pdf-frame-content: 'date_box';
 13                top: 2.4cm;
 14                left: 2.8cm;
 15             }  
 16             @frame {
 17                -pdf-frame-content: "content";
 18                top: 16.7cm;
 19                margin-right: 2.8cm;
 20                margin-left: 2.8cm;
 21             }  
 22        }    
 23     </style>
 24     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 25 </head>
The @page block contains some general document/page properties, such as page format (line 4) - in this example we want our document to be 210x297 (vertical and horizontal dimensions respectively described in mm).  @frame keywords define layout positioning information. For example, lines 5-10 could be represented in regular CSS like this:

 1 div#footer {
 2     top: 25.8cm;
 3     margin-right: 2.8cm;
 4     margin-left: 2.8cm;
 5 }      


So it is now easy to imagine what this layout looks like, it contains a date-box, regular content (in the middle of the document) and a footer.

You can place your data in the corresponding box the following way:

<div id="date_box" style="text-align:right; font-size: 20px;">
2012/04/26
</div>

<div id="content" style="text-align:left; font-size: 14px;">
This is a pisa layout test
</div>

<div id="footer" style="text-align:center; font-size: 10px;">
This should be a footer
</div>

In order to generate the PDF from the command line, simply run:

~ pisa my_html_file.html

This will create my_html_file.pdf in the same director.
You may also achieve this the pythonic way - see my previous post about PDF generation.

For more information about layout definition and supported CSS styles check the official pisa documentation.

~KR

P.S. I don't usually do front-end stuff, but I really like this tool.




1 comment:

free counters