Reportlab. Floating Text with two Columns
Asked Answered
N

2

8

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.

Nata answered 5/12, 2012 at 9:51 Comment(0)
S
17

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)
Slier answered 6/12, 2012 at 18:31 Comment(1)
Thanks. Platypus is the way to go here. Changed my def pdf to your example and works perfect. thumps up :)Nata
O
6

If you want to do this in plain ReportLab you'll have to figure out where to break the paragraph yourself. If you instead use Platypus to set up a document class, you can specify the frames to lay text out in on the page and the order of the frames will determine where things flow over to. When the paragraph reaches the end of the first frame on the left of the page, the content will automatically flow over into the next frame, which you can position on the right of the page to achieve what you want.

Ochre answered 6/12, 2012 at 14:35 Comment(1)
This is a good explanation of how it actually works, thank you.Laney

© 2022 - 2024 — McMap. All rights reserved.