def begin(self, name='', typ=''): styleSheet = getSampleStyleSheet() self.code = styleSheet['Code'] self.bt = styleSheet['BodyText'] self.story = [] # Cover page t = time.gmtime(time.time()) timeString = time.strftime("%Y-%m-%d %H:%M", t) self.story.append( Paragraph( '<font size=18>Documentation for %s "%s"</font>' % (typ, name), self.bt)) self.story.append( Paragraph( '<font size=18>Generated by: graphdocpy.py version %s</font>' % __version__, self.bt)) self.story.append( Paragraph('<font size=18>Date generated: %s</font>' % timeString, self.bt)) self.story.append( Paragraph('<font size=18>Format: PDF</font>', self.bt)) self.story.append(PageBreak()) # Table of contents toc = TableOfContents() self.story.append(toc) self.story.append(PageBreak())
def _showWidgetProperties(self, widget): """Dump all properties of a widget.""" props = widget.getProperties() keys = props.keys() keys.sort() lines = [] for key in keys: value = props[key] f = getStringIO() pprint.pprint(value, f) value = f.getvalue()[:-1] valueLines = string.split(value, '\n') for i in range(1, len(valueLines)): valueLines[i] = ' ' * (len(key) + 3) + valueLines[i] value = string.join(valueLines, '\n') lines.append('%s = %s' % (key, value)) text = join(lines, '\n') self.story.append( Paragraph("<i>Properties of Example Widget</i>", self.bt)) self.story.append(Paragraph("", self.bt)) self.story.append(Preformatted(text, self.code))
def _showFunctionDemoCode(self, function): """Show a demo code of the function generating the drawing.""" # Heading self.story.append(Paragraph("<i>Example</i>", self.bt)) self.story.append(Paragraph("", self.bt)) # Sample code codeSample = inspect.getsource(function) self.story.append(Preformatted(codeSample, self.code))
def beginClass(self, name, doc, bases): bt = self.bt story = self.story if bases: bases = map(lambda b: b.__name__, bases) # hack story.append(Paragraph('%s(%s)' % (name, join(bases, ', ')), bt)) else: story.append(Paragraph(name, bt)) story.append(XPreformatted(doc, bt))
def beginClass(self, name, doc, bases): bt = self.bt story = self.story if bases: bases = [b.__name__ for b in bases] # hack story.append(Paragraph('%s(%s)' % (name, ', '.join(bases)), bt)) else: story.append(Paragraph(name, bt)) story.append(XPreformatted(doc, bt))
def wrap(self, availWidth, availHeight): """Adds hyperlink to toc entry.""" widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: if reportlab.Version <= '2.3': _tempEntries = [(0, 'Placeholder for table of contents', 0)] else: _tempEntries = [(0, 'Placeholder for table of contents', 0, None)] else: _tempEntries = self._lastEntries if _tempEntries: base_level = _tempEntries[0][0] else: base_level = 0 tableData = [] for entry in _tempEntries: level, text, pageNum = entry[:3] left_col_level = level - base_level if reportlab.Version > '2.3': # For ReportLab post-2.3 leftColStyle=self.getLevelStyle(left_col_level) else: # For ReportLab <= 2.3 leftColStyle = self.levelStyles[left_col_level] label = self.refid_lut.get((level, text), None) if label: pre = u'<a href="%s" color="%s">' % (label, self.linkColor) post = u'</a>' if not isinstance(text, unicode): text = unicode(text, 'utf-8') text = pre + text + post else: pre = '' post = '' #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % left_col_level, parent=leftColStyle, leftIndent=0, alignment=TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(pre+str(pageNum)+post, rightColStyle) tableData.append([leftPara, rightPara]) self._table = Table(tableData, colWidths=widths, style=self.tableStyle) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return self.width, self.height
def test(self): stylesheetHy = getSampleStyleSheet() sth = stylesheetHy['Normal'] sth.fontName = 'Helvetica' sth.fontSize = 32 sth.leading = 36 sth.language = 'DE' sth.hyphenation = True # von Hand getippt, # geht mit und ohne Trennung (kein Zeilenumbruch) text = u"""<para>Ungefähr ein Jahr ist es her, </para>""".encode( "utf8") # von Hand getippt, # geht mit und ohne Trennung (Zeilenumbruch) # text = u"""<para>Ungefähr ein Jahr ist es her, dass CDU-Ministerpraesident</para>""".encode("utf8") # von Hand getippt, # geht nur ohne Trennung (Zeilenumbruch plus Umlaut im Wort) # erzeugt bei Trennung Traceback [1] # text = u"""<para>Ungefähr ein Jahr ist es her, dass CDU-Ministerpräsident</para>""".encode("utf8") # von tagesschau.de kopiert und eingesetzt, # geht ohne, aber nicht mit Trennung # erzeugt bei Trennung gleichen Traceback [1] text = u"""<para>Ungefähr ein Jahr ist es her, dass CDU-Ministerpräsident Jürgen Rüttgers sich anschickte, die SPD links zu überholen. Denn auf seine Initiative hin beschlossen die Christdemokraten, die Bezugsdauer für ältere ALG-I-Empfänger zu Lasten von Jüngeren zu verlängern. So war das in der Berliner Koalition zwar nicht gedacht - aber Rüttgers setzte auf dem Parteitag von Dresden den Beschluss für eine längere Zahldauer trotzdem durch. Umgesetzt allerdings wurde der von der Großen Koalition nie.</para>""".encode( "utf8") p = Paragraph(text, sth) story = [p] doc = SimpleDocTemplate("test_simple.pdf") doc.build(story)
def __init__(self, text, style, bulletText=None, caseSensitive=1, level=0, snum=None, parent_id=None, node=None): #if label is None: # it happens #self.label = text.replace(u'\xa0', ' ').strip( #).replace(' ', '-').encode('ascii', 'replace').lower() #else: #self.label = label.strip() # Issue 114: need to convert "&" to "&" and such. # Issue 140: need to make it plain text self.stext=re.sub(r'<[^>]*?>', '', unescape(text)) self.stext = self.stext.strip() self.level = int(level) self.snum = snum self.parent_id=parent_id self.node=node Paragraph.__init__(self, text, style, bulletText)
def draw(self): # Add outline entry self.canv.bookmarkHorizontal(self.parent_id,0,0+self.height) if self.canv.firstSect: self.canv.sectName = self.stext self.canv.firstSect=False if self.snum is not None: self.canv.sectNum = self.snum else: self.canv.sectNum = "" self.canv.addOutlineEntry(self.stext.encode('utf-8','replace'), self.parent_id.encode('utf-8','replace'), int(self.level), False) Paragraph.draw(self)
def makeParagraphs(txt, style): """Convert plain text into a list of paragraphs.""" lines = txt.split("\n") retval = [ Paragraph(line[:6] == '<para>' and line or ('<para>%s</para>' % line), style) for line in lines ] return retval
def _showWidgetDemoCode(self, widget): """Show a demo code of the widget.""" # Heading #className = widget.__class__.__name__ self.story.append(Paragraph("<i>Example</i>", self.bt)) # Sample code codeSample = inspect.getsource(widget.__class__.demo) self.story.append(Preformatted(codeSample, self.code))
def _showDrawingCode(self, drawing): """Show code of the drawing class.""" # Heading #className = drawing.__class__.__name__ self.story.append(Paragraph("<i>Example</i>", self.bt)) # Sample code codeSample = inspect.getsource(drawing.__class__.__init__) self.story.append(Preformatted(codeSample, self.code))
def emit(f, o): if len(f): if "PRE" in o: # Preformatted txt = "\n".join(f) story.append(XPreformatted(txt, stylesheet["Code"])) else: txt = " ".join([s.strip() for s in f]) story.append(Paragraph(txt, stylesheet["BodyText"])) del o[:] del f[:]
def beginClass(self, name, doc, bases): "Append a graphic demo of a Widget or Drawing at the end of a class." if VERBOSE: print('GraphPdfDocBuilder.beginClass(%s...)' % name) aClass = eval('self.skeleton.moduleSpace.' + name) if issubclass(aClass, Widget): if self.shouldDisplayModule: modName, modDoc, imported = self.shouldDisplayModule self.story.append( Paragraph( modName, self.makeHeadingStyle(self.indentLevel - 2, 'module'))) self.story.append(XPreformatted(modDoc, self.bt)) self.shouldDisplayModule = 0 self.hasDisplayedModule = 1 if self.shouldDisplayClasses: self.story.append( Paragraph('Classes', self.makeHeadingStyle(self.indentLevel - 1))) self.shouldDisplayClasses = 0 PdfDocBuilder0.beginClass(self, name, doc, bases) self.beginAttributes(aClass) elif issubclass(aClass, Drawing): if self.shouldDisplayModule: modName, modDoc, imported = self.shouldDisplayModule self.story.append( Paragraph( modName, self.makeHeadingStyle(self.indentLevel - 2, 'module'))) self.story.append(XPreformatted(modDoc, self.bt)) self.shouldDisplayModule = 0 self.hasDisplayedModule = 1 if self.shouldDisplayClasses: self.story.append( Paragraph('Classes', self.makeHeadingStyle(self.indentLevel - 1))) self.shouldDisplayClasses = 0 PdfDocBuilder0.beginClass(self, name, doc, bases)
def beginAttributes(self, aClass): "Append a list of annotated attributes of a class." self.story.append( Paragraph('Public Attributes', self.makeHeadingStyle(self.indentLevel + 1))) map = aClass._attrMap if map: map = sorted(map.items()) else: map = [] for name, typ in map: if typ != None: if hasattr(typ, 'desc'): desc = typ.desc else: desc = '<i>%s</i>' % typ.__class__.__name__ else: desc = '<i>None</i>' self.story.append(Paragraph("<b>%s</b> %s" % (name, desc), self.bt)) self.story.append(Paragraph("", self.bt))
def generatePDF(self, model_data): """ Dieses Beispiel zeigt nicht annähernd die Möglichkeiten von ReportLab! Es demonstriert nur, wie einfach es sein kann. """ stylesheet = getSampleStyleSheet() stn = stylesheet['Normal'] text = """ PDF Layout not implemented.<br> Please add a method <font face="Courier">generatePDF(self, data_model)</font> to your Layout class. The method should generate a ReportLab Platypus story from the data_model and store it in <font face="Courier">self.story</font>. """ para = Paragraph(text.decode("iso-8859-1"), stn) self.story = [para]
def beginFunctions(self, names): if names: self.story.append(Paragraph('Functions', self.bt))
def run(): for language, fname, title in [ ("DE", "dokumentation_de", u"wordaxe Anleitung (deutsch)"), ("EN", "dokumentation_en", u"wordaxe User Guide (english)"), ]: print("Generating", fname + ".pdf") stylesheet = getSampleStyleSheet() for name in ["Heading1", "Heading2", "Heading3", "Code", "BodyText"]: style = stylesheet[name] style.language = language style.hyphenation = True doc = SimpleDocTemplate(fname + ".pdf", title=title, author="Henning von Bargen", pagesize=pagesizes.portrait(pagesizes.A4), allowSplitting=1) # Content einlesen und parsen content = open(fname + ".txt").read() story = [] frags = [] opts = [] def emit(f, o): if len(f): if "PRE" in o: # Preformatted txt = "\n".join(f) story.append(XPreformatted(txt, stylesheet["Code"])) else: txt = " ".join([s.strip() for s in f]) story.append(Paragraph(txt, stylesheet["BodyText"])) del o[:] del f[:] for zeile in content.splitlines(): # Umkodieren nach utf8 zeile = zeile.decode("iso-8859-1").encode("utf8") zstrip = zeile.strip() # Überschrift? level = 0 while zeile.startswith("=") and zeile.endswith("="): level += 1 zeile = zeile[1:-1] if level > 0: emit(frags, opts) stil = "Heading%d" % level story.append(Paragraph(zeile, stylesheet[stil])) elif zstrip == "" and not "PRE" in opts: emit(frags, opts) elif zstrip == "{{{": emit(frags, opts) opts.append("PRE") elif zstrip == "}}}": emit(frags, opts) else: frags.append(zeile) emit(frags, opts) doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
story.append(Paragraph(txt, stylesheet["BodyText"])) del o[:] del f[:] for zeile in content.splitlines(): # Dekodieren zeile = zeile.decode("iso-8859-1") zstrip = zeile.strip() # Überschrift? level = 0 while zeile.startswith("=") and zeile.endswith("="): level += 1 zeile = zeile[1:-1] if level > 0: emit(frags, opts) stil = "Heading%d" % level story.append(Paragraph(zeile, stylesheet[stil])) elif zstrip == "" and not "PRE" in opts: emit(frags, opts) elif zstrip == "{{{": emit(frags, opts) opts.append("PRE") elif zstrip == "}}}": emit(frags, opts) else: frags.append(zeile) emit(frags, opts) doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
def beginPackage(self, name): DocBuilder0.beginPackage(self, name) self.story.append(Paragraph(name, self.bt))
def genParagraphList(self, style): return [Paragraph(toUnicode(value), style) for value in self.values()]
def gen_elements(node, depth, in_line_block=False, style=styles['BodyText']): global decoration if isinstance (node, docutils.nodes.document): node.elements=gather_elements(node,depth,style=style) ####################### ## Tables ####################### elif isinstance (node, docutils.nodes.table): node.elements=gather_elements(node,depth) elif isinstance (node, docutils.nodes.tgroup): rows=[] hasHead=False for n in node.children: if isinstance (n,docutils.nodes.thead): hasHead=True for row in n.children: r=[] for cell in row.children: r.append(cell) rows.append(r) elif isinstance (n,docutils.nodes.tbody): for row in n.children: r=[] for cell in row.children: r.append(cell) rows.append(r) spans=filltable (rows) data=[] for row in rows: r=[] for cell in row: if isinstance(cell,str): r.append("") else: r.append(gather_elements(cell,depth)) data.append(r) st=spans+tstyleNorm if hasHead: st+=[tstyleHead] node.elements=[Table(data,style=TableStyle(st))] elif isinstance (node, docutils.nodes.title): # Special cases: (Not sure this is right ;-) if isinstance (node.parent, docutils.nodes.document): # FIXME maybe make it a coverpage? node.elements=[Paragraph(gen_pdftext(node,depth), styles['Title'])] elif isinstance (node.parent, docutils.nodes.topic): # FIXME style correctly node.elements=[Paragraph(gen_pdftext(node,depth), styles['Heading3'])] elif isinstance (node.parent, docutils.nodes.admonition) or \ isinstance (node.parent, docutils.nodes.sidebar): node.elements=[Paragraph(gen_pdftext(node,depth), styles['Heading3'])] else: node.elements=[Paragraph(gen_pdftext(node,depth), styles['Heading%d'%min(depth,3)])] elif isinstance (node, docutils.nodes.subtitle): if isinstance (node.parent,docutils.nodes.sidebar): node.elements=[Paragraph(gen_pdftext(node,depth), styles['Heading4'])] elif isinstance (node.parent,docutils.nodes.document): node.elements=[Paragraph(gen_pdftext(node,depth), styles['Subtitle'])] elif isinstance (node, docutils.nodes.paragraph): node.elements=[Paragraph(gen_pdftext(node,depth), style)] elif isinstance (node, docutils.nodes.docinfo): # A docinfo usually contains several fields. # We'll render it as a series of elements, one field each. node.elements=gather_elements(node,depth,style=style) elif isinstance (node, docutils.nodes.field): # A field has two child elements, a field_name and a field_body. # We render as a two-column table, left-column is right-aligned, # bold, and much smaller fn=Paragraph(gather_pdftext(node.children[0],depth)+":",style=styles['FieldName']) fb=gen_elements(node.children[1],depth) node.elements=[Table([[fn,fb]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None])] elif isinstance (node, docutils.nodes.decoration): # This is a tricky one. We need to switch our document's # page templates based on this. If decoration contains a # header and/or a footer, we need to use those # right now, we avoid trouble. # FIXME Implement node.elements=gather_elements(node,depth,style=style) elif isinstance (node, docutils.nodes.header): decoration['header']=Paragraph(gather_pdftext(node,depth),style=styles['Footer']) node.elements=[] elif isinstance (node, docutils.nodes.footer): decoration['footer']=Paragraph(gather_pdftext(node,depth),style=styles['Footer']) node.elements=[] elif isinstance (node, docutils.nodes.author): if isinstance (node.parent,docutils.nodes.authors): # Is only one of multiple authors. Return a paragraph node.elements=[Paragraph(gather_pdftext(node,depth), style=style)] else: # A single author: works like a field fb=gather_pdftext(node,depth) node.elements=[Table([[Paragraph("Author:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None])] elif isinstance (node, docutils.nodes.authors): # Multiple authors. Create a two-column table. Author references on the right. td=[[Paragraph("Authors:",style=styles['FieldName']),gather_elements(node,depth,style=style)]] node.elements=[Table(td,style=tstyles['Field'],colWidths=[fieldlist_lwidth,None])] elif isinstance (node, docutils.nodes.organization): fb=gather_pdftext(node,depth) t=Table([[Paragraph("Organization:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None]) node.elements=[t] elif isinstance (node, docutils.nodes.contact): fb=gather_pdftext(node,depth) t=Table([[ Paragraph("Contact:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None]) node.elements=[t] elif isinstance (node, docutils.nodes.address): fb=gather_pdftext(node,depth) t=Table([[ Paragraph("Address:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None]) node.elements=[t] elif isinstance (node, docutils.nodes.version): fb=gather_pdftext(node,depth) t=Table([[ Paragraph("Version:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None]) node.elements=[t] elif isinstance (node, docutils.nodes.revision): fb=gather_pdftext(node,depth) t=Table([[ Paragraph("Revision:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None]) node.elements=[t] elif isinstance (node, docutils.nodes.status): fb=gather_pdftext(node,depth) t=Table([[ Paragraph("Version:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None]) node.elements=[t] elif isinstance (node, docutils.nodes.date): fb=gather_pdftext(node,depth) t=Table([[ Paragraph("Date:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None]) node.elements=[t] elif isinstance (node, docutils.nodes.copyright): fb=gather_pdftext(node,depth) t=Table([[Paragraph("Copyright:",style=styles['FieldName']), Paragraph(fb,style) ]],style=tstyles['Field'],colWidths=[fieldlist_lwidth,None]) node.elements=[t] elif isinstance (node, docutils.nodes.topic) \ or isinstance (node, docutils.nodes.field_body) \ : node.elements=gather_elements(node,depth,style=style) elif isinstance (node, docutils.nodes.section): if depth<page_break_level: node.elements=[PageBreak()]+gather_elements(node,depth+1) else: node.elements=gather_elements(node,depth+1) elif isinstance (node, docutils.nodes.bullet_list) \ or isinstance (node, docutils.nodes.enumerated_list) \ or isinstance (node, docutils.nodes.definition_list) \ or isinstance (node, docutils.nodes.option_list) \ or isinstance (node, docutils.nodes.field_list) \ or isinstance (node, docutils.nodes.definition) \ : node.elements=gather_elements(node,depth,style=style) elif isinstance (node, docutils.nodes.option_list_item): og = gather_elements(node.children[0],depth,style) desc = gather_elements(node.children[1],depth,style) node.elements=[Table([[og,desc]],style=tstyles['Field'])] elif isinstance (node, docutils.nodes.definition_list_item): # I need to catch the classifiers here tt=[] dt=[] for n in node.children: if isinstance(n,docutils.nodes.term) or \ isinstance(n,docutils.nodes.classifier) : tt.append(gather_pdftext(n,depth,style)) else: dt=dt+gen_elements(n,depth,style) node.elements=[Paragraph(':'.join(tt),style),MyIndenter(left=10)]+dt+[MyIndenter(left=-10)] elif isinstance (node, docutils.nodes.list_item): # A list_item is a table of two columns. # The left one is the bullet itself, the right is the # item content. This way we can nest them. el=gather_elements(node,depth,style=style) b="" if node.parent.get('bullet') or isinstance(node.parent,docutils.nodes.bullet_list): # FIXME: use correct bullet symbols, check inter-paragraph spacing b=str(node.parent.get('bullet')) if b=="None": b="" elif node.parent.get ('enumtype')=='arabic': b=str(node.parent.children.index(node)+1)+'.' elif node.parent.get ('enumtype')=='lowerroman': b=str(lowerroman[node.parent.children.index(node)])+'.' elif node.parent.get ('enumtype')=='upperroman': b=str(lowerroman[node.parent.children.index(node)].upper())+'.' elif node.parent.get ('enumtype')=='loweralpha': b=str(loweralpha[node.parent.children.index(node)])+'.' elif node.parent.get ('enumtype')=='upperalpha': b=str(loweralpha[node.parent.children.index(node)].upper())+'.' else: print "Unknown kind of list_item" print node.parent sys.exit(1) el[0].bulletText = b node.elements=el elif isinstance (node, docutils.nodes.transition): node.elements=[Separation()] elif isinstance (node, docutils.nodes.system_message) \ or isinstance (node, docutils.nodes.problematic) \ : # FIXME show the error in the document, red, whatever sys.stderr.write (node.astext()+"\n") sys.stderr.flush() node.elements=[] elif isinstance (node, docutils.nodes.block_quote): node.elements=[MyIndenter(left=20)]+gather_elements(node,depth,style)+[MyIndenter(left=-20)] elif isinstance (node, docutils.nodes.attribution): node.elements=[Paragraph(gather_pdftext(node,depth),styles['Attribution'])] elif isinstance (node, docutils.nodes.comment): # Class that generates no output node.elements=[] elif isinstance (node, docutils.nodes.line_block): # Obsolete? Let's do something anyway. # FIXME: indent or not? qstyle=copy(style) qstyle.leftIndent+=30 node.elements=gather_elements(node,depth,style=qstyle) elif isinstance (node, docutils.nodes.line): # All elements in one line node.elements=[Paragraph(gather_pdftext(node,depth),style=style)] elif isinstance (node, docutils.nodes.literal_block) \ or isinstance (node, docutils.nodes.doctest_block) \ or isinstance (node, docutils.nodes.option) \ : node.elements=[PreformattedFit(gather_pdftext(node,depth,replaceEnt=False),styles['Code'])] elif isinstance (node, docutils.nodes.attention) \ or isinstance (node, docutils.nodes.caution) \ or isinstance (node, docutils.nodes.danger) \ or isinstance (node, docutils.nodes.error) \ or isinstance (node, docutils.nodes.hint) \ or isinstance (node, docutils.nodes.important) \ or isinstance (node, docutils.nodes.note) \ or isinstance (node, docutils.nodes.tip) \ or isinstance (node, docutils.nodes.warning) \ or isinstance (node, docutils.nodes.admonition) \ : node.elements=[Paragraph(node.tagname.title(),style=styles['Heading3'])]+gather_elements(node,depth,style=style) elif isinstance (node, docutils.nodes.image): # FIXME handle all the other attributes i=Image(filename=str(node.get("uri"))) if node.get('align'): i.hAlign=node.get('align').upper() node.elements=[i] elif isinstance (node, docutils.nodes.figure): # The sub-elements are the figure and the caption, and't ugly if # they separate node.elements=[KeepTogether(gather_elements(node,depth,style=style))] elif isinstance (node, docutils.nodes.caption): node.elements=[Paragraph('<i>'+gather_pdftext(node,depth)+'</i>',style=style)] elif isinstance (node, docutils.nodes.legend): node.elements=gather_elements(node,depth,style=style) elif isinstance (node, docutils.nodes.sidebar): node.elements=[Table([[ gather_elements(node,depth,style=style)]],style=tstyles['Sidebar'])] elif isinstance (node, docutils.nodes.rubric): node.elements=[Paragraph(gather_pdftext(node,depth),styles['Rubric'])] elif isinstance (node, docutils.nodes.compound): # FIXME think if this is even implementable node.elements=gather_elements(node,depth,style) elif isinstance (node, docutils.nodes.container): # FIXME think if this is even implementable node.elements=gather_elements(node,depth,style) elif isinstance (node, docutils.nodes.substitution_definition): node.elements=[] elif isinstance (node, docutils.nodes.tbody): rows=[gen_elements(n,depth) for n in node.children] t=[] for r in rows: if not r: continue t.append(r) node.elements=[Table(t,style=tstyles['Normal'])] elif isinstance (node, docutils.nodes.footnote): # It seems a footnote contains a label and a series of elements label=Paragraph(gather_pdftext(node.children[0],depth),style) contents=gather_elements(node,depth,style)[1:] decoration['endnotes'].append([label,contents]) node.elements=[] elif isinstance (node, docutils.nodes.label): node.elements=[Paragraph(gather_pdftext(node,depth),style)] elif isinstance (node, docutils.nodes.Text): node.elements=[Paragraph(gather_pdftext(node,depth),style)] elif isinstance (node, docutils.nodes.entry): node.elements=gather_elements(node,depth,style) # FIXME nodes we are ignoring for the moment elif isinstance (node, docutils.nodes.target) \ or isinstance (node, docutils.nodes.footnote) \ or isinstance (node, docutils.nodes.citation) \ or isinstance (node, docutils.nodes.reference) \ or isinstance (node, docutils.nodes.raw) \ : node.elements=[] else: print "Unkn. node (gen_elements): ", node.__class__ print node sys.exit(1) # set anchors for internal references for id in node['ids']: node.elements.insert( node.elements and isinstance(node.elements[0], PageBreak) and 1 or 0, Paragraph('<a name="%s"/>'%id,style)) return node.elements
def generatePDF(self, model_data): """ Dieses Beispiel zeigt nicht annähernd die Möglichkeiten von ReportLab! Es demonstriert nur, wie einfach es sein kann. """ stylesheet = getSampleStyleSheet() # Formatstil für die Überschrift festlegen sth1 = stylesheet['Heading1'] # Formatstil für den Absatz festlegen stn = stylesheet['Normal'] stn.fontName = 'Helvetica' stn.fontSize = 10 stn.leading = 12 #print stn.spaceAfter #print stn.spaceBefore #print stn.leading print("TODO: Why is the text so close to the top of the cells?") # Automatische Silbentrennung für diesen Stil einschalten stn.language = 'DE' stn.hyphenation = True # Wir machen erstmal einen Fake, # nämlich den ASCII-Text zeilenweise. self.generateDUMP(model_data) pure_text = "".join(self.text) story = [] para = Paragraph( "Beispiel für einen Datenbankbericht".decode("iso-8859-1"), sth1) ''' story.append(para) para = Paragraph("""Dies ist ein längerer Absatz, der eigentlich nur den Zweck hat, die automatische Silbentrennung von WordAxe zu demonstrieren. Aus diesem Grund enthält dieser Absatz auch einige besonders schöne lange Wörter wie etwa "Donaudampfschifffahrtsgesellschaftskapitän" oder "Bundeskanzleramt" oder "Landesgesundheitsbehörden", sogar gleich mehrfach: Schiff Dampfschiff Dampfschifffahrt Donaudampfschiffahrt oder Donaudampfschiffahrtsgesellschaft Donaudampfschiffahrtsgesellschaftsvorsitzender (Ha! damit habt Ihr wohl nicht gerechnet, oder?) und nebenbei auch HTML-Formatierung wie <b>fett</b> oder <i>kursiv!</i> Mal sehen, ob das Euro-Zeichen geht - ich befürchte aber, dass das auf Anhieb nicht funktioniert. Hier kommt es: € - nee, das sehe ich schon im Quelltext nicht richtig. """.decode("iso-8859-1"), stn) story.append(para) for line in pure_text.splitlines(): para = Paragraph(line.decode("iso-8859-1"), stn) story.append(para) ''' # Jetzt mal anders: # Ausgabe als Master-Detail-Liste, wobei die Details # eine Spalte weiter eingerückt sind. if model_data: headers1 = [Paragraph(toUnicode(x), stn) for x in DEPT.headers()] headers2 = [None] + [ Paragraph(toUnicode(x), stn) for x in EMP.headers() ] nColumns = max(len(headers1), len(headers2)) fill1 = ([None] * (nColumns - len(headers1))) fill2 = ([None] * (nColumns - len(headers2))) headers1 += fill1 headers2 += fill2 tableData = [headers1, headers2] colWidths = [None] * nColumns colWidths[-1] = 40 * mm nRows = len(model_data) tableStyle = TableStyle([ ('BOX', (0, 0), (-1, -1), 1, colors.black), ('BACKGROUND', (0, 0), (-1, 1), colors.orange), ('BACKGROUND', (0, 1), (-1, 1), colors.yellow), ('INNERGRID', (0, 0), (-1, -1), 0.5, colors.black), ('LEFTPADDING', (0, 0), (-1, -1), 3), ('RIGHTPADDING', (0, 0), (-1, -1), 3), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ]) for dept in model_data: tableData.append(dept.genParagraphList(stn) + fill1) tableStyle.add('BACKGROUND', (0, len(tableData) - 1), (-1, len(tableData) - 1), colors.orange) for emp in dept.children["emp"]: tableData.append([""] + emp.genParagraphList(stn) + fill2) table = LongTable(tableData, style=tableStyle, colWidths=colWidths, repeatRows=2) story.append(table) self.story = story
def beginModule(self, name, doc, imported): story = self.story bt = self.bt story.append(Paragraph(name, bt)) story.append(XPreformatted(doc, bt))
def beginFunction(self, name, doc, sig): bt = self.bt story = self.story story.append(Paragraph(name + sig, bt)) story.append(XPreformatted(doc, bt))
def beginClasses(self, names): self.story.append(Paragraph('Classes', self.bt))