我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用reportlab.lib.units.inch()。
def add_header(self): # # aiddata logo # logo = self.assets_dir + '/templates/aid_data.png' # im = Image(logo, 2.188*inch, 0.5*inch) # im.hAlign = 'LEFT' # self.Story.append(im) # self.Story.append(Spacer(1, 0.25*inch)) # title ptext = '<font size=20>AidData GeoQuery Request Documentation</font>' self.Story.append(Paragraph(ptext, self.styles['Center'])) # report generation info
def run(): objects_to_draw = [] from reportlab.lib.styles import ParagraphStyle #from paragraph import Paragraph from reportlab.platypus.doctemplate import SimpleDocTemplate #need a style normal = ParagraphStyle('normal') normal.firstLineIndent = 18 normal.spaceBefore = 6 from reportlab.lib.randomtext import randomText import random for i in range(15): height = 0.5 + (2*random.random()) box = XBox(6 * inch, height * inch, 'Box Number %d' % i) objects_to_draw.append(box) para = Paragraph(randomText(), normal) objects_to_draw.append(para) SimpleDocTemplate('doctemplate.pdf').build(objects_to_draw, onFirstPage=myFirstPage,onLaterPages=myLaterPages)
def test2(canv,testpara): #print test_program; return from reportlab.lib.units import inch from reportlab.lib.styles import ParagraphStyle from reportlab.lib import rparsexml parsedpara = rparsexml.parsexmlSimple(testpara,entityReplacer=None) S = ParagraphStyle("Normal", None) P = Para(S, parsedpara) (w, h) = P.wrap(5*inch, 10*inch) print("wrapped as", (h,w)) canv.saveState() canv.translate(1*inch, 1*inch) canv.rect(0,0,5*inch,10*inch, fill=0, stroke=1) P.canv = canv canv.saveState() P.draw() canv.restoreState() canv.setStrokeColorRGB(1, 0, 0) #canv.translate(0, 3*inch) canv.rect(0,0,w,h, fill=0, stroke=1) canv.restoreState() canv.showPage()
def __init__(self, value='', **args): if type(value) is type(1): value = asNative(value) for (k, v) in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 MultiWidthBarcode.__init__(self, value)
def computeSize(self, *args): barWidth = self.barWidth oa, oA = ord('a') - 1, ord('A') - 1 w = 0.0 for c in self.decomposed: oc = ord(c) if c in ascii_lowercase: w = w + barWidth * (oc - oa) elif c in ascii_uppercase: w = w + barWidth * (oc - oA) if self.barHeight is None: self.barHeight = w * 0.15 self.barHeight = max(0.25 * inch, self.barHeight) if self.quiet: w += self.lquiet + self.rquiet self._height = self.barHeight self._width = w
def __init__(self, value='', **args): if type(value) == type(1): value = str(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = min(inch * 0.25, self.barWidth * 10.0) self.rquiet = min(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value)
def test_03_draw(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch c = Canvas('demo.pdf', pagesize=A4) c.translate(inch,inch) c.setFont("Helvetica", 14) c.setStrokeColorRGB(0.2,0.5,0.3) c.setFillColorRGB(1,0,1) c.line(0,0,0,1.7*inch) c.line(0,0,1*inch,0) c.rect(0.2*inch, 0.2*inch, 1*inch, 1.5*inch,fill=1) c.rotate(90) c.setFillColorRGB(0,0,0.77) c.drawString(0.3*inch, -inch, "Hello World") c.showPage() c.save()
def test_06_fontsize(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.colors import red, magenta c = Canvas('demo.pdf', pagesize=A4) c.translate(inch, inch) c.setFont("Times-Roman", 20) c.setFillColor(red) c.saveState() c.drawCentredString(2.75*inch, 2.5*inch,"Font size excmples") c.setFillColor(magenta) size = 7 x = 2.3 * inch y = 1.3 * inch for line in range(7): c.setFont("Helvetica", size) c.drawRightString(x, y, "%s points" % size) c.drawString(x,y, "test") y = y-size*1.2 size = size+1.5 c.restoreState() c.drawString(0,0, "%s" % c.getAvailableFonts()) c.showPage() c.save()
def add_str_content(self, content, size=9, Bold=False, indent=(0.05*inch, 0.05*inch), style=None): ''' ?????? :param content: ?????? :param size: ????,??9 :param Bold: ????,??False :param indent: ??????,(???,???) :param style: ???? ''' if style == None: style = styles["Normal"] __content = "<font name='chsFont' size=%s>%s</font>" % (size, content) if Bold: __content = "<b>%s</b>" % __content p = Paragraph(__content, style) self.__content.append(Spacer(PAGE_WIDTH, indent[0])) self.__content.append(p) self.__content.append(Spacer(PAGE_WIDTH, indent[1]))
def _add_page_outline(self, canvas): start_posn = self.start_posn canvas.setLineWidth(2) canvas.rect(cm, cm, PAGE_WIDTH-2*cm, PAGE_HEIGHT-2*cm) canvas.drawImage(LOGO_PATH, 0.5*inch, start_posn, height=0.5*inch, width=1.875*inch) canvas.setFont('Helvetica-Bold', 24) canvas.drawRightString(PAGE_WIDTH-(0.5*inch), start_posn + 0.15*inch, 'REGISTRATION FORM') footer_text = 'This form created on ' footer_text += datetime.now().strftime('%Y-%m-%d %I:%M:%S %p') canvas.setFont('Helvetica', 9) canvas.drawRightString(PAGE_WIDTH-(0.5*inch), 0.5*inch, footer_text) self.start_posn = start_posn - 0.4 * inch sales_rep_text = 'BOOKING REP: ' if self.user.first_name or self.user.last_name: sales_rep_text += self.user.first_name + ' ' + self.user.last_name else: sales_rep_text += self.user.username canvas.setFont('Helvetica-Bold', 9.5) canvas.drawString(0.5*inch, 0.5*inch, sales_rep_text)
def _add_conference_details(self, canvas): start_posn = self.start_posn canvas.setFillColor(colors.blue) canvas.setFont('Helvetica', 10) canvas.drawString(0.5*inch, start_posn, 'Section A - Conference Information') canvas.setFillColor(colors.black) canvas.setLineWidth(1) canvas.rect(0.5*inch, start_posn - 0.4*inch, PAGE_WIDTH-inch, 0.3*inch) canvas.line(2.5*inch, start_posn - 0.4*inch, 2.5*inch, start_posn - 0.1*inch) canvas.setFillColor(colors.red) canvas.drawString(0.7*inch, start_posn-0.3*inch, self.event.number) canvas.setFillColor(colors.black) canvas.drawString(2.7*inch, start_posn-0.3*inch, self.event.title) self.start_posn = start_posn - 0.65 * inch
def _add_event_options(self, canvas): start_posn = self.start_posn num_options = len(self.details['event_options']) canvas.setFont('Helvetica', 10) canvas.setLineWidth(1) canvas.setFillColor(colors.blue) canvas.drawString(0.5*inch, start_posn, 'Conference Options Selected') canvas.setFillColor(colors.black) canvas.rect(0.5*inch, start_posn-(0.1+num_options*0.3)*inch, PAGE_WIDTH-inch, num_options*0.3*inch) option_start = start_posn - 0.3 * inch for option in self.details['event_options']: event_option = EventOptions.objects.get(pk=option) option_text = event_option.name + ': ' option_text += event_option.startdate.strftime('%-d %B, %Y') if event_option.enddate != event_option.startdate: option_text += ' to ' option_text += event_option.enddate.strftime('%-d %B, %Y') canvas.drawString(0.7 * inch, option_start, option_text) canvas.line(0.5*inch, option_start-(0.1*inch), PAGE_WIDTH-0.5*inch, option_start-(0.1*inch)) option_start -= 0.3 * inch self.start_posn = option_start - 0.05 * inch
def _add_notes(self, canvas): """ This is designed to be the last element on the page. Don't move it or stuff will break """ start_posn = self.start_posn start_posn = self.start_posn canvas.setFillColor(colors.blue) canvas.setFont('Helvetica', 10) canvas.drawString(0.5*inch, start_posn, 'Section E - Registration Notes') canvas.setFillColor(colors.black) canvas.rect(0.5*inch, 0.75*inch, PAGE_WIDTH-inch, start_posn-0.85*inch) style_sheet = getSampleStyleSheet() style = style_sheet['BodyText'] para = Paragraph(self.details['registration_notes'], style) h=para.wrap(7.1 * inch, start_posn-0.65*inch)[1] para.drawOn(canvas, 0.7 * inch, start_posn-h-0.2*inch)
def test_0(self): "Test length attribute conversion." mapping = ( ("0", 0), ("316", 316), ("-316", -316), ("-3.16", -3.16), ("-1e-2", -0.01), ("1e-5", 1e-5), ("1e1cm", 10*cm), ("1e1in", 10*inch), ("1e1%", 10), ("-8e-2cm", (-8e-2)*cm), ("20px", 20), ("20pt", 20 * 1.25), ("1.5em", 12 * 1.5), ) ac = svglib.Svg2RlgAttributeConverter() failed = _testit(ac.convertLength, mapping) assert len(failed) == 0 assert ac.convertLength("1.5em", em_base=16.5) == 24.75
def add_timeline(self): ptext = '<b><font size=14>Processing Timeline</font></b>' self.Story.append(Paragraph(ptext, self.styles['Normal'])) self.Story.append(Spacer(1, 0.1*inch)) data = [ [self.request['stage'][0]['name'], self.time_str(self.request['stage'][0]['time'])], [self.request['stage'][1]['name'], self.time_str(self.request['stage'][1]['time'])], [self.request['stage'][2]['name'], self.time_str(self.request['stage'][2]['time'])], [self.request['stage'][3]['name'], self.time_str(int(time.time()))] # ['complete', self.time_str(self.request['stage'][3]['time'])] ] data = [[i[0], pg(i[1], 1)] for i in data] t = Table(data) t.setStyle(TableStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black) ])) self.Story.append(t)
def __init__(self, text=[], target='your website', pdfName='Report.pdf'): self.__target = target self.__pdfName = self.__path + pdfName self.__text = text if not os.path.exists('result/'): os.mkdir(r'result/') time = datetime.datetime.today() date = time.strftime("%h-%d-%Y %H:%M:%S") c = canvas.Canvas(self.__pdfName) c.setPageSize((16 * inch,22 * inch)) textobj = c.beginText() textobj.setTextOrigin(inch, 20 * inch) textobj.textLines(''' This is the scanning report of %s. ''' %self.__target) textobj.textLines(''' Date: %s ''' % date) for line in self.__text: textobj.textLine(line.strip()) c.drawText(textobj) c.showPage() c.save()
def mainPageFrame(canvas, doc): "The page frame used for all PDF documents." canvas.saveState() pageNumber = canvas.getPageNumber() canvas.line(2*cm, A4[1]-2*cm, A4[0]-2*cm, A4[1]-2*cm) canvas.line(2*cm, 2*cm, A4[0]-2*cm, 2*cm) if pageNumber > 1: canvas.setFont('Times-Roman', 12) canvas.drawString(4 * inch, cm, "%d" % pageNumber) if hasattr(canvas, 'headerLine'): # hackish # HVB: Changed fr Hyphenation support # headerline = string.join(canvas.headerLine, ' \xc2\x8d ') headerline = string.join(canvas.headerLine, ' \xc2\x8d '.decode('utf8')) canvas.drawString(2*cm, A4[1]-1.75*cm, headerline) canvas.setFont('Times-Roman', 8) msg = "Generated with docpy. See http://www.reportlab.com!" canvas.drawString(2*cm, 1.65*cm, msg) canvas.restoreState()
def create_logo(self, absolute_path): image = Image(absolute_path) image._restrictSize(2.5 * inch, 2.5 * inch) return image
def _header_footer(self, canvas, doc): # Save the state of our canvas so we can draw on it canvas.saveState() styles = getSampleStyleSheet() style_right = ParagraphStyle(name='right', parent=styles['Normal'], fontName='Helvetica', fontSize=10, alignment=TA_RIGHT) # Header fieldsight_logo = Image('http://' + self.base_url +'/static/images/fs1.jpg') fieldsight_logo._restrictSize(1.5 * inch, 1.5 * inch) # headerleft = Paragraph("FieldSight", styles['Normal']) headerright = Paragraph(self.project_name, style_right) # w1, h1 = headerleft.wrap(doc.width, doc.topMargin) w2, h2 = headerright.wrap(doc.width, doc.topMargin) textWidth = stringWidth(self.project_name, fontName='Helvetica', fontSize=10) fieldsight_logo.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin + 12) headerright.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin + 20) project_logo = Image('http://' + self.base_url + self.project_logo) project_logo._restrictSize(0.4 * inch, 0.4 * inch) project_logo.drawOn(canvas, headerright.width + doc.leftMargin -0.5 * inch - textWidth, doc.height + doc.topMargin + 10) # header.drawOn(canvas, doc.leftMargin + doc.width, doc.height + doc.topMargin +20) # Footer footer = Paragraph('Page no. '+str(canvas._pageNumber), style_right) w, h = footer.wrap(doc.width, doc.bottomMargin) footer.drawOn(canvas, doc.leftMargin, h + 40) # Release the canvas canvas.restoreState()
def __init__(self, background=None): Figure.__init__(self, 3*inch, 3*inch) self.caption = 'Figure 1 - a blank page' self.captionStyle = captionStyle self.background = background
def drawFigure(self): drawPage(self.canv, 0.625*inch, 0.25*inch, 1.75*inch, 2.5*inch) self.canv.translate(0.625*inch, 0.25*inch) self.canv.scale(1.75/8.27, 2.5/11.69) self.drawVirtualPage()
def demo1(canvas): frame = Frame( 2*inch, # x 4*inch, # y at bottom 4*inch, # width 5*inch, # height showBoundary = 1 # helps us see what's going on ) bodyStyle = ParagraphStyle('Body', fontName=_baseFontName, fontSize=24, leading=28, spaceBefore=6) para1 = Paragraph('Spam spam spam spam. ' * 5, bodyStyle) para2 = Paragraph('Eggs eggs eggs. ' * 5, bodyStyle) mydata = [para1, para2] #this does the packing and drawing. The frame will consume #items from the front of the list as it prints them frame.addFromList(mydata,canvas)
def myFirstPage(canvas, doc): from reportlab.lib.colors import red PAGE_HEIGHT = canvas._pagesize[1] canvas.saveState() canvas.setStrokeColor(red) canvas.setLineWidth(5) canvas.line(66,72,66,PAGE_HEIGHT-72) canvas.setFont(_baseFontNameB,24) canvas.drawString(108, PAGE_HEIGHT-108, "TABLE OF CONTENTS DEMO") canvas.setFont(_baseFontName,12) canvas.drawString(4 * inch, 0.75 * inch, "First Page") canvas.restoreState()
def test(): from pprint import pprint #print test_program; return from reportlab.pdfgen import canvas from reportlab.lib.units import inch fn = "paratest0.pdf" c = canvas.Canvas(fn) test2(c,testparagraph) test2(c,testparagraph1) if 1: remainder = test_program + test_program + test_program laststate = {} while remainder: print("NEW PAGE") c.translate(inch, 8*inch) t = c.beginText() t.setTextOrigin(0,0) p = paragraphEngine() p.resetState(laststate) p.x = 0 p.y = 0 maxwidth = 7*inch maxheight = 500 (formattedprogram, remainder, laststate, height) = p.format(maxwidth, maxheight, remainder) if debug: pprint( formattedprogram )#; return laststate = p.runOpCodes(formattedprogram, c, t) c.drawText(t) c.showPage() print("="*30, "x=", laststate["x"], "y=", laststate["y"]) c.save() print(fn)
def __init__(self, atx=0, aty=0, width=2.5*inch, height=1.5*inch, powered_by=0): self.origin = (atx, aty) self.dimensions = (width, height) self.powered_by = powered_by
def toLength(s): '''convert a string to a length''' try: if s[-2:]=='cm': return float(s[:-2])*cm if s[-2:]=='in': return float(s[:-2])*inch if s[-2:]=='pt': return float(s[:-2]) if s[-1:]=='i': return float(s[:-1])*inch if s[-2:]=='mm': return float(s[:-2])*mm if s[-4:]=='pica': return float(s[:-4])*pica return float(s) except: raise ValueError("Can't convert '%s' to length" % s)
def computeSize(self, *args): barWidth = self.barWidth wx = barWidth * self.ratio if self.gap == None: self.gap = barWidth w = 0.0 for c in self.decomposed: if c in 'sb': w = w + barWidth elif c in 'SB': w = w + wx else: # 'i' w = w + self.gap if self.barHeight is None: self.barHeight = w * 0.15 self.barHeight = max(0.25 * inch, self.barHeight) if self.bearers: self.barHeight = self.barHeight + self.bearers * 2.0 * barWidth if self.quiet: w += self.lquiet + self.rquiet self._height = self.barHeight self._width = w
def __init__(self, value = "", **args): value = asNative(value) for k, v in args.items(): setattr(self, k, v) if self.quiet: if self.lquiet is None: self.lquiet = max(inch * 0.25, self.barWidth * 10.0) self.rquiet = max(inch * 0.25, self.barWidth * 10.0) else: self.lquiet = self.rquiet = 0.0 Barcode.__init__(self, value)
def header(self, canvas, doc): canvas.saveState() canvas.setFont('Times-Roman', 9) canvas.drawString(inch, A4[1] - 50, TITLE_MSG) canvas.line(inch, A4[1] - 60, A4[0] - 65, A4[1] - 60) canvas.restoreState()
def footer(self, canvas, doc): canvas.saveState() canvas.setFont('Times-Roman', 9) canvas.drawString(inch, 0.75 * inch, PAGE_MSG.format(doc.page) ) canvas.restoreState()
def Initialize( self ): from reportlab.lib import colors self.canv.setLineCap( 1 ) self.canv.setLineJoin( 1 ) self.unit = inch self.apertures = {} self.macroDefinitions = {} self.px = 0.0 self.py = 0.0 self.x = 0.0 self.y = 0.0 self.i = 0.0 self.j = 0.0 self.path = None self.polyPath = None self.leadingZeroSuppression = 1 self.absolute = 1 self.inch = 1 self.xFormat = (2,3) self.yFormat = (2,3) self.tool = None self.toolWidth = None self.dnumber = 2 self.nCodeLimit = 4 self.gCodeLimit = 2 self.dCodeLimit = 2 self.mCodeLimit = 2 self.linearInterpolation = 1 self.clockWise = 1 self.singleQuadrant = 1 self.interpolationScale = 1.0 self.areaFill = 0 self.fgColor = colors.Color(0.8,0.8,0.8) self.bgColor = colors.Color(1,1,1) self.curFgColor = self.fgColor self.curBgColor = self.bgColor self.canv.setStrokeColor(self.curFgColor) self.canv.setFillColor(self.curFgColor)
def HandleMO( self, str ): if str[-3:] == "IN*": self.unit = inch elif str[-3:] == "MM*": self.unit = mm # }}} # {{{ HandleLP
def ProcessFile( self, fname ): f = open( fname ) print "Processing file: %s" % fname scanner = GerberScanner( f, fname ) try: while 1: token = scanner.read() if token[0] is None: break if token[0] == 'block': if token[1] == "M02" or token[1] == "M2": self.HandleBlock( "M02*" ) else: self.HandleBlock( token[1] ) elif token[0] == 'pblock': self.HandleParameterBlock( token[1] ) elif token[0] == 'mblock': self.HandleMacro( token[1] ) except GerberError, message: name, line, col = scanner.position() print "Error in file %s, line %s, column %s" % (name,line,col) print message print "Finished: Extents are (%4.2f, %4.2f) - (%4.2f, %4.2f) (in.)" %(gerberExtents[0] / inch, gerberExtents[1] / inch, gerberExtents[2] / inch, gerberExtents[3] / inch) f.close() return gerberExtents # }}} # }}} # {{{ Translate (filelist)
def myFirstPage(self, canvas, doc): canvas.saveState() canvas.setFont("Times-Bold", 16) canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108, self.Title) canvas.setFont("Times-Roman", 9) canvas.drawString(inch, 0.75*inch, "First Page / %s"% self.pageinfo) canvas.restoreState()
def myLaterPage(self, canvas, doc): canvas.saveState() canvas.setFont("Times-Roman", 9) canvas.drawString(inch, 0.75*inch, "First Page / %s"% self.pageinfo) canvas.restoreState()
def go(self): doc = SimpleDocTemplate("demo.pdf") Story = [Spacer(1, 2*inch)] style = styles["Normal"] for i in range(100): bogustext = ("This is Paragraph number %s. " % i) * 20 p = Paragraph(bogustext, style) Story.append(p) Story.append(Spacer(1, 0.2*inch)) doc.build(Story, onFirstPage=self.myFirstPage, onLaterPages=self.myLaterPage)
def test_04_canvasMethods(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch c = Canvas('demo.pdf', pagesize=A4) c.translate(inch,inch) c.setFont("Helvetica", 14) c.setAuthor("JY.zenist.song") c.setTitle("Hello ReportLib") c.drawString(3*inch, 3*inch, "Hello World") c.showPage() c.save()
def test_07_registerFont(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) c = Canvas('demo.pdf', pagesize=A4) c.translate(inch, inch) c.setFont('chsFont', 32) c.drawString(0,0,"??????????") c.showPage() c.save()
def test_08_table(self): from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph, Table from reportlab.lib.units import inch from reportlab.lib.enums import TA_JUSTIFY from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib import fonts, colors pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">AUT OOM????</font>', stylesheet['Title'])) elements.append(Spacer(1,12)) stylesheet.add(ParagraphStyle(name="Justify", alignment=TA_JUSTIFY)) stylesheet['Justify'].contName = 'chsFont' data = [] data.append(["???","???","???"]) data.append(["120","6","50"]) ts = [('INNERGRID',(0,0),(-1,-1),0.25, colors.black),("BOX",(0,0),(-1,-1),0.25,colors.black),('FONT',(0,0),(-1,-1), 'chsFont')] table = Table(data, 2.1*inch, 0.24*inch, ts) elements.append(table) doc.build(elements)
def test_22_lineCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.linecharts import HorizontalLineChart import random pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title'])) elements.append(Spacer(1,1*inch)) d = Drawing(400,200) data = [ [13,5,20,22,37,45,19,4], # [14,6,21,23,38,46,20,5] ] for i in range(500): data[0].append(random.randint(1,100)) # data[1].append(random.randint(1,100)) lc = HorizontalLineChart() lc.x = 50 lc.y = 50 lc.height = 180 lc.width = 300 lc.data = data lc.joinedLines = 1 # lc.categoryAxis.categoryNames = data[0] d.add(lc) elements.append(d) doc.build(elements)
def test_23_linePlotCharts(self): from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib.units import inch from reportlab.platypus import SimpleDocTemplate, Spacer, Paragraph from reportlab.pdfbase import pdfmetrics from reportlab.graphics.shapes import Drawing from reportlab.pdfbase.ttfonts import TTFont from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics.widgets.markers import makeMarker pdfmetrics.registerFont(TTFont('chsFont', 'STHeiti Light.ttc')) stylesheet = getSampleStyleSheet() elements = [] doc = SimpleDocTemplate("demo.pdf") elements.append(Paragraph('<font name="chsFont">JY.zenist.song - ??</font>', stylesheet['Title'])) elements.append(Spacer(1,1*inch)) d = Drawing(400,200) data = [ [(1,1), (2,2), (2.5,1), (3,3), (4,5)], ] lp = LinePlot() lp.x = 5 lp.y = 5 lp.height = 190 lp.width = 390 lp.data = data lp.joinedLines = 1 lp.lines[0].symbol = makeMarker('FilledCircle') d.add(lp) elements.append(d) doc.build(elements)
def __init__(self, fileName,**kw): SimpleDocTemplate.__init__(self,fileName,**kw) self.leftMargin, self.rightMargin = 0.5*inch,0.5*inch self.topMargin,self.bottomMargin = 0.5*inch,0.5*inch
def __myFirstPage(self, canvas, doc): '''???????''' canvas.saveState() canvas.setFont("chsFont", 16) canvas.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108, self.TITLE) canvas.setFont("chsFont", 9) canvas.drawString(inch, 0.75*inch, "Copy Right @%s"% self.PAGE_INFO) canvas.restoreState()
def __myLaterPage(self, canvas, doc): '''???????''' canvas.saveState() canvas.setFont("chsFont", 9) canvas.drawString(inch, 0.75*inch, "Copy Right @%s"% self.PAGE_INFO) canvas.restoreState()
def add_empty_line(self, lines=1): '''????''' self.__content.append(Spacer(PAGE_WIDTH, 0.3*inch*lines))
def _add_delegate_information(self, canvas): start_posn = self.start_posn canvas.setFillColor(colors.blue) canvas.setFont('Helvetica', 10) canvas.drawString(0.5*inch, start_posn, 'Section B - Delegate Information') canvas.setLineWidth(1) canvas.setFillColor(colors.black) canvas.rect(0.5*inch, start_posn-1.3*inch, PAGE_WIDTH-inch, 1.2*inch) canvas.line(2.5*inch, start_posn-1.3*inch, 2.5*inch, start_posn-0.1*inch) canvas.drawString(0.7 * inch, start_posn-0.3*inch, 'Delegate Name:') name = '' if self.details['salutation'].strip() != '': name += self.details['salutation'].strip() + ' ' if self.details['first_name'].strip != '': name += self.details['first_name'].strip() + ' ' name += self.details['last_name'].strip() canvas.drawString(2.7 * inch, start_posn-0.3*inch, name) canvas.line(0.5*inch, start_posn-0.4*inch, PAGE_WIDTH-0.5*inch, start_posn-0.4*inch) canvas.drawString(0.7*inch, start_posn-0.6*inch, 'Delegate Title:') canvas.drawString(2.7*inch, start_posn-0.6*inch, self.details['title'].strip()) canvas.line(0.5*inch, start_posn-0.7*inch, PAGE_WIDTH-0.5*inch, start_posn-0.7*inch) canvas.drawString(0.7*inch, start_posn-0.9*inch, 'Email:') canvas.drawString(2.7*inch, start_posn-0.9*inch, self.details['email1'].strip()) canvas.line(0.5*inch, start_posn-1.0*inch, PAGE_WIDTH-0.5*inch, start_posn-1.0*inch) canvas.drawString(0.7*inch, start_posn-1.2*inch, 'Phone:') canvas.drawString(2.7*inch, start_posn-1.2*inch, self.details['phone1'].strip()) self.start_posn = start_posn-1.55*inch
def _add_company_information(self, canvas): start_posn = self.start_posn canvas.setFillColor(colors.blue) canvas.setFont('Helvetica', 10) canvas.drawString(0.5*inch, start_posn, 'Section C: Company Information') canvas.setFillColor(colors.black) canvas.rect(0.5*inch, start_posn-1.2*inch, PAGE_WIDTH-inch, 1.1*inch) canvas.line(2.5*inch, start_posn-1.2*inch, 2.5*inch, start_posn-0.1*inch) canvas.drawString(0.7*inch, start_posn-0.3*inch, 'Company Name:') canvas.drawString(2.7*inch, start_posn-0.3*inch, self.details['name'].strip()) canvas.line(0.5*inch, start_posn-0.4*inch, PAGE_WIDTH-0.5*inch, start_posn-0.4*inch) canvas.drawString(0.7*inch, start_posn-0.6*inch, 'Mailing Address:') address = '' if self.details['address1'].strip() != '': address += self.details['address1'].strip() + '<br/>' if self.details['address2'].strip() != '': address += self.details['address2'].strip() + '<br/>' if self.details['city'].strip() != '' or \ self.details['state_prov'].strip() != '': if self.details['city'].strip() != '': address += self.details['city'].strip() + ', ' address += self.details['state_prov'].strip() + '<br/>' if self.details['postal_code'].strip() != '': address += self.details['postal_code'].strip() + ' ' address += self.details['country'].strip() style_sheet = getSampleStyleSheet() style = style_sheet['BodyText'] para = Paragraph(address, style) h = para.wrap(4.7 * inch, 0.9* inch)[1] para.drawOn(canvas, 2.7 * inch, start_posn-h-0.45*inch) self.start_posn = start_posn-1.45*inch
def _add_assistant_details(self, canvas): start_posn = self.start_posn canvas.setFillColor(colors.blue) canvas.setFont('Helvetica', 10) canvas.drawString(0.5*inch, start_posn, 'Assistant Details') canvas.setFillColor(colors.black) canvas.rect(0.5*inch, start_posn-0.9*inch, PAGE_WIDTH-inch, 0.8*inch) canvas.line(2.5*inch, start_posn-0.9*inch, 2.5*inch, start_posn-0.1*inch) canvas.drawString(0.7*inch, start_posn-0.3*inch, 'Assistant:') assistant_deets = '' new_line = False if self.details['assistant_salutation'].strip() != '': new_line = True assistant_deets += self.details['assistant_salutation'].strip() + ' ' if self.details['assistant_first_name'].strip() != '': new_line = True assistant_deets += self.details['assistant_first_name'].strip() + ' ' if self.details['assistant_last_name'].strip() != '': new_line = True assistant_deets += self.details['assistant_last_name'].strip() + ' ' if new_line: assistant_deets += '<br/>' if self.details['assistant_title'].strip() != '': assistant_deets += self.details['assistant_title'].strip() assistant_deets += '<br/>' if self.details['assistant_email'].strip() != '': assistant_deets += 'Email: ' assistant_deets += self.details['assistant_email'] + '<br/>' if self.details['assistant_phone'].strip() != '': assistant_deets += 'Phone: ' + self.details['assistant_phone'] style_sheet = getSampleStyleSheet() style = style_sheet['BodyText'] para = Paragraph(assistant_deets, style) h = para.wrap(4.7*inch, 0.8*inch)[1] para.drawOn(canvas, 2.7*inch, start_posn-h-0.15*inch) self.start_posn = start_posn-1.1*inch