In my last post, I presented how to place text in an absolute position on a page. You will not want to do this all the time. Imagine putting a book of text in PDF form that way. An exercise in masochism to be sure. ReportLab offers a spectacular framework, called platypus, for building real documents. There are tons of new terms to learn here, so I will try to be thorough. Here is some example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/usr/bin/env python from reportlab.lib.pagesizes import letter from reportlab.lib.styles import ParagraphStyle from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer doc = SimpleDocTemplate("paragraphs.pdf", pagesize=letter) parts = [] style = ParagraphStyle( name='Normal', fontName='Helvetica-Bold', fontSize=9, ) parts.append(Paragraph("Paragraphs are a kind of Flowable. " * 20, style)) parts.append(Spacer(1, 0.2 * inch)) parts.append(Paragraph("Paragraphs are natural in their behavior. " * 20, style)) parts.append(Spacer(1, 0.2 * inch)) parts.append(Paragraph( "Paragraphs make sense for flexible and dynamic documents. " * 20, style)) doc.build(parts) |
The first point of interest is line 7. SimpleDocTemplate is just what it sounds like. It provides information to control the behavior of the flowables. It is also used to write the PDF to disk. You can write your own Templates to offer features like multiple columns. I will cover that in another post.
On lines 10 to 14, we are defining a ParagraphStyle. This lets you define how your text will be displayed, like font and alignment. You might be wondering about the name. This is required. It is used when the ParagraphStyle is part of a StyleSheet, which I will cover in another post.
Now, we are ready to build a Paragraph object. This is the Flowable I have been talking about. In ReportLab, Flowables are objects that have wrapping, positioning, and splitting behavior defined. A Paragraph will stay within the margins and span across pages without trouble. They only require some text and a ParagraphStyle.
A Spacer is another Flowable. It is just whitespace. It takes two arguments, width and height.
When we are ready to write the PDF, we call our doc's, our SimpleDocTemplate instance's, build method with a collection of Flowables.
