[reportlab-users] how to get rid of some empty space?

Viktor Nagy viktor.nagy at toolpart.hu
Sun Dec 19 11:09:22 EST 2010


Hi,

this is the first time I use reportlab/platypus to create a pdf. I've found
it to be really nice and easy to use, except for one factor, that I could
not come over. Could someone more experienced help me out, please?

The following code generates a sample of what I want, if you run it, you'll
see that there is a huge empty space between the "headers" and the line
plots. I would like to reduce this space.

thank you, Viktor

--------- the code follows ---------

import os
from reportlab.lib import colors, pagesizes
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.graphics import shapes
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.platypus import BaseDocTemplate, Paragraph, Spacer, Frame,
PageTemplate, FrameBreak, NextPageTemplate, KeepTogether
from reportlab.rl_config import defaultPageSize

PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]

styles = {}
def edit_styles():
global mystyles
def_styles = getSampleStyleSheet()
styles['normal'] = def_styles['Normal']
styles['normal'].fontSize = 9
styles['normal'].leading = 10

styles['title'] = def_styles['Title']
styles['title'].fontSize = 14
styles['title'].spaceAfter = 0

styles['h1'] = def_styles['h1']
styles['h1'].fontSize = 12
styles['h1'].backColor = '#cccccc'
styles['h1'].leading = 14
styles['h1'].alignment = 1
styles['h1'].spaceAfter = 0
styles['h1'].spaceBefore = 2

class MetamobDocTemplate(BaseDocTemplate):

def afterInit(self):
'''
Set up the first and later pages for two column layout and title
frame on the first page.
'''
self.leftMargin = self.bottomMargin = 40
self.width = self.width + 80
self.height = self.height + 40

frameWidth = self.width/2
frameHeight = self.height-.05*inch
titleHeight = 0.75*inch


frames = [Frame(self.leftMargin, self.bottomMargin, frameWidth,
frameHeight,
id='left', showBoundary=False, rightPadding=3,
leftPadding=3),
Frame(self.leftMargin + frameWidth, self.bottomMargin,
frameWidth,
frameHeight, id='right', showBoundary=False,
rightPadding=3, leftPadding=3)]

first_page_frames = [Frame(self.leftMargin, self.bottomMargin +
frameHeight-titleHeight,
self.width, titleHeight, id='top',
showBoundary=False),
Frame(self.leftMargin, self.bottomMargin, frameWidth,
frameHeight-titleHeight,
id='left', showBoundary=False, rightPadding=3,
leftPadding=3),
Frame(self.leftMargin + frameWidth, self.bottomMargin,
frameWidth,
frameHeight-titleHeight, id='right',
showBoundary=False, rightPadding=3, leftPadding=3)]

template = [PageTemplate(frames=first_page_frames, id='first_page',
onPage=self.first_page()),
PageTemplate(frames=frames, id='later_pages',
onPage=self.later_pages())]
self.addPageTemplates(template)

def first_page(self):
def real_first_page(canvas, doc):
canvas.saveState()
canvas.setFont('Times-Bold',14)
canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-50,
self.title)
canvas.setFont('Times-Roman',9)
canvas.drawString(inch, 0.75 * inch, "Page %d" % doc.page)
canvas.restoreState()
return real_first_page

def later_pages(self):
def real_later_pages(canvas, doc):
canvas.saveState()
canvas.setFont('Times-Roman',9)
canvas.drawString(inch, 0.75 * inch, "Page %d - %s" % (doc.page,
self.title))
canvas.restoreState()
return real_later_pages

class Report(object):

frames = {}
story = []

def __init__(self, title, file_name):
edit_styles()
self.title = title
self.file_name = file_name
self.document = MetamobDocTemplate(self.file_name, title=self.title,
pagesize=pagesizes.A4)

def generate(self):
self.document.build(self.story)
return self.file_name

def add_text(self, text):
'''
Adds text to the document, or frame if `to_frame` is specified.

:param text: text to be added
'''
para = Paragraph(text.replace('\n', '<br/>'), styles['normal'])
self.story.append(para)
self.story.append(FrameBreak())
self.story.append(NextPageTemplate("later_pages"))

def add_chart(self, title, data, extra_text=''):
'''
Create a chart with a title, and text below it

The data should be in the form of

(data_list, x_axis_points, y_axis_points)

where `data_list`, `x_axis_points` and `y_axis_points' are a list of
the data to be shown,
a list of ticks to be marked on the x, and y axes respectively.

:param title: the title string
:param data: the data list
:param extra_text: an optional string to be shown below the graph
'''
chart = []
title = Paragraph(title, styles['h1'])
chart.append(title)

drawing = shapes.Drawing(145, 210)
lp = LinePlot()
lp.x = 30
lp.y = 20
lp.height = 120
lp.width = 170
lp.data = [ data.values() ]
lp.joinedLines = 1
lp.lines[0].symbol = makeMarker('FilledCircle')
lp.lines[1].symbol = makeMarker('Circle')
lp.lineLabelFormat = '%2.0f'
lp.strokeColor = colors.black

lp.xValueAxis.valueMin = 1
lp.xValueAxis.valueMax = len(data.keys())
lp.xValueAxis.valueSteps = range(len(data.keys()))
lp.xValueAxis.labelTextFormat = data.keys()

y_values = [y for x, y in data.values()]
lp.yValueAxis.valueMin = min(y_values)
lp.yValueAxis.valueMax = max(y_values)
lp.yValueAxis.valueSteps = y_values
drawing.add(lp)

chart.append(drawing)

if extra_text:
para = Paragraph(extra_text.replace('\n', '<br/>'),
styles['normal'])
chart.append(para)

self.story.append(KeepTogether(chart))


def go():
report = Report('A nice report', 'phello.pdf')

text = '''INTERVAL: 08.11.2010 - 24.11.2010
ANGAJAT: AAAAAAAAAAAAAAAA
OPTIUNI INTERVAL: ZILE
OPTIUNI AFISARE: OPERATII
'''
report.add_text(text)

data = {'2010a': (1,1),
'2011a': (2,2),
'2012a': (3,1.5),
'2013a': (4,3),
'2014a': (5,5),
}
for i in range(10):
report.add_chart('%d chart' % i, data, 'hello\n bello')

filename = report.generate()
# go_open(filename)

def go_open(file_name):
if os.name == "nt":
os.filestart("%s" % file_name)
elif os.name == "posix":
os.system("/usr/bin/xdg-open %s" % file_name)

if __name__ == '__main__':
go()

--
ToolPart Team Ltd
6725 Szeged, Boldogasszony sgt. 65.
Info: +36 30 430 4971
Tel.: +36 62 469 321
Fax: +36 62 426 738
E-mail: toolpart at toolpart.hu
Web: www.toolpart.hu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://two.pairlist.net/pipermail/reportlab-users/attachments/20101219/807dcdcf/attachment.htm>


More information about the reportlab-users mailing list