Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reportlab. Floating Text with two Columns

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.

like image 762
user1878514 Avatar asked Dec 05 '12 09:12

user1878514


2 Answers

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)
like image 83
Ocaso Protal Avatar answered Dec 03 '22 06:12

Ocaso Protal


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.

like image 26
G Gordon Worley III Avatar answered Dec 03 '22 07:12

G Gordon Worley III