Reportlab. Floating Text with two Columns

user1878514 picture user1878514 · Dec 5, 2012 · Viewed 7.9k times · Source

First of all, I'm new to python, reportlab, xhtml2pdf. I've already done my first pdf files with reportlab, but I ran into the following problem.

I need a large text in two columns.

First I create my canvas, create my story, append my large text as a paragraph to the story, create my Frame and finally add the story to the frame.

c = Canvas("local.pdf")
storyExample = []
textExample = (""" This is a very large text Lorem Ipsum ... """)
storyExample.append(Paragraph(textExample, styleText))
frameExample = Frame(0, 0, 50, 50,showBoundary=0)
frameExample.addFromList(storyExample,c)
c.showPage()
c.save()

Works like a charm. But I need to show the text in a two column represantation.

Now the text just flows threw my frame like:

|aaaaaaaaaaaaaaaaaaaa|
|bbbbbbbbbbbbbbbbbbbb|
|cccccccccccccccccccc|
|dddddddddddddddddddd|

But I need it like this:

|aaaaaaaaa  bbbbbbbbbb|
|aaaaaaaaa  cccccccccc|
|bbbbbbbbb  cccccccccc|
|bbbbbbbbb  dddddddddd|

I hope you understood what I am trying to say.

Answer

Ocaso Protal picture Ocaso Protal · Dec 6, 2012

This can be done using BaseDocTemplate and Frame as you can read here. I modified that receipe to only use a two frame layout:

from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, PageBreak, PageTemplate
from reportlab.lib.styles import getSampleStyleSheet
import random

words = "lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et".split()

styles=getSampleStyleSheet()
Elements=[]

doc = BaseDocTemplate('basedoc.pdf',showBoundary=1)

#Two Columns
frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1')
frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2')

Elements.append(Paragraph(" ".join([random.choice(words) for i in range(1000)]),styles['Normal']))
doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1,frame2]), ])


#start the construction of the pdf
doc.build(Elements)