def test_CustomElementInsidePara(self): # It's just too hard to write a standard test with a custom renderer. doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append('This is a standard paragraph with the default style.') class CustomClass(object): pass p.append(CustomClass()) section.append(p) # Define renderer with custom element support. specialString = "ABC I'm unique" def customElementWriter(renderer, element): renderer._write(specialString) r = Renderer(write_custom_element_callback=customElementWriter) # Render with custom element. result = StringIO() r.Write(doc, result) testData = result.getvalue() result.close() # Confirm generate result has custom rendering. assert specialString in testData
def main(): """ Main processing for command line invocation """ cmdline = process_command_line() cfg = json.load(file(cmdline.configfile)) if cmdline.lang: langs = [cmdline.lang] else: langs = LANGS if cmdline.wiki: for lang in sorted(langs): conv = SubdimensionsToWikiConverter(lang,cfg[lang]) conv.create_cms_schemas() conv.create_lms() ofname = lang + '_' + cmdline.outfile lines = conv.get_wiki_pages() with codecs.open(ofname,"w",encoding="utf-8") as of: for line in lines: print >> of, line else: plog = {} if cmdline.prevlog: plog = json.load(file(cmdline.prevlog),encoding='utf-8') doc = Document() section = Section() doc.Sections.append(section) ss = doc.StyleSheet logdoc = {} for lang in sorted(langs): conv = SubdimensionsConverter(lang,cfg[lang],plog) conv.set_ss(ss) conv.add_tables(section) conv.add_to_json(logdoc) DR = Renderer() ofile = codecs.open(cmdline.outfile, "w", encoding="utf-8") DR.Write( doc, ofile ) lfile = codecs.open(cmdline.outfile+'.log', "w", encoding="utf-8") json.dump(logdoc, lfile, indent=2, encoding='utf-8') return 0
def render(self, output): document = Document() section = Section() for o in output: section.append(o) document.Sections.append(section) renderer = Renderer() renderer.Write(document, StringIO()) # Setup instance variables renderer._doc = document renderer._fout = StringIO() renderer._CurrentStyle = "" renderer._WriteSection(section, True, False) return renderer._fout.getvalue()
def test_ExceptionOnUnknownElement(self): # Create document with unknown element type. doc, section, styles = RTFTestCase.initializeDoc() class CustomClass(object): pass section.append(CustomClass()) # Try to render. r = Renderer() result = StringIO() self.assertRaises(Exception, r.Write, doc, result)
def render(self, output): from cStringIO import StringIO from rtfng.Elements import Document from rtfng.document.section import Section from rtfng.Renderer import Renderer document = Document() section = Section() for o in output: section.append(o) document.Sections.append(section) renderer = Renderer() renderer.Write(document, StringIO()) # Setup instance variables renderer._doc = document renderer._fout = StringIO() renderer._CurrentStyle = "" renderer._WriteSection(section, True, False) return renderer._fout.getvalue()
for grant in person['grants']: try: print 'grant',\ int(grant['start_date']['date']['year']), int(year) except: continue if int(grant['start_date']['date']['year']) >= int(year): para_props = ParagraphPropertySet() para_props.SetFirstLineIndent(TabPropertySet.DEFAULT_WIDTH*-1) para_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH*2) p = Paragraph(ss.ParagraphStyles.Normal, para_props) p.append(vt.string_from_grant(grant)) section.append(p) if len(person['publications']) > 0: for publication in person['publications']: try: print 'pub', int(publication['date']['year']), int(year) except: continue if int(publication['date']['year']) >= int(year): para_props = ParagraphPropertySet() para_props.SetFirstLineIndent(TabPropertySet.DEFAULT_WIDTH*-1) para_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH*2) p = Paragraph(ss.ParagraphStyles.Normal, para_props) p.append(vt.string_from_document(publication)) section.append(p) print str(datetime.datetime.now()) Renderer().Write(doc, file("report.rtf", "w"))
int(grant['end_date']['date']['month']), int(grant['end_date']['date']['day'])) + \ datetime.timedelta(days=3*365) > datetime.datetime.now(): key = grant['end_date']['date']['year'] + grant['title'] grants[key] = grant print grants for key in sorted(grants.keys(), reverse=True): grant = grants[key] para_props = ParagraphPropertySet() para_props.SetFirstLineIndent(-720) para_props.SetLeftIndent(720) p = Paragraph(ss.ParagraphStyles.Normal, para_props) if 'role' in grant and grant['role'] == 'pi': grant_role = 'Principal Investigator' elif 'role' in grant and grant['role'] == 'coi': grant_role = 'Co-investigator' elif 'role' in grant and grant['role'] == 'inv': grant_role = 'Investigator' else: grant_role = '' p.append(grant['start_date']['datetime'][0:10], ' - ', grant['end_date']['datetime'][0:10], ', ', grant['title'], ', ', grant['awarded_by'], ', ', grant['sponsor_award_id'], ', ', grant_role) section.append(p) # All Done. Write the file Renderer().Write(doc, file("biosketch.rtf", "w")) print str(datetime.datetime.now())
def generateReport(window, plot, evals, lagranges): """Save session report to rtf document """ fileName = Qt.QFileDialog.getSaveFileName(window, u'Сохранить отчет', '.', 'Word (*.doc)') if not fileName.isNull(): doc = Document() #ss = doc.StyleSheet section = Section() doc.Sections.append(section) minX, maxX, minY, maxY = plot.getBounds() section.append(u'Полотно растеризации:') section.append('') table = Table(TabPropertySet.DEFAULT_WIDTH, \ TabPropertySet.DEFAULT_WIDTH * 3, \ TabPropertySet.DEFAULT_WIDTH * 3) table.AddRow(Cell(Paragraph(u'ось')), Cell(Paragraph(u'от')), Cell(Paragraph(u'до'))) table.AddRow(Cell(Paragraph('x')), Cell(Paragraph(str(minX))), Cell(Paragraph(str(maxX)))) table.AddRow(Cell(Paragraph('y')), Cell(Paragraph(str(minY))), Cell(Paragraph(str(maxY)))) section.append(table) section.append(u'Детализация: %d %s на график' % (plot.width(), langMorph(plot.width(), (u'точек', u'точка', u'точки')))) section.append(Paragraph(getPlotImage(plot))) section.append('') section.append(u'%d %s:' % (len(evals), langMorph(len(evals), (u'функций', u'функция', u'функции')))) #for s in evals: # section.append('f(x) = %s' % s) for i in evals: section.append('f(x) = %s' % i.getExpression()) section.append('') section.append(u'%d %s Лагранжа' % (len(lagranges), langMorph(len(lagranges), (u'полиномов', u'полином', u'полинома')))) for i in lagranges: points = i.count() section.append(ur'\u2014' * 30) section.append( u'%d %s:' % (points, langMorph(points, (u'точек', u'точка', u'точки')))) table = Table(TabPropertySet.DEFAULT_WIDTH / 2, \ TabPropertySet.DEFAULT_WIDTH * 3, \ TabPropertySet.DEFAULT_WIDTH * 3) for j in xrange(points): table.AddRow(Cell(Paragraph('%d' % j)), Cell(Paragraph('%g' % i.pointX[j])), Cell(Paragraph('%g' % i.pointY[j]))) section.append(table) section.append(u'L(x) = %s' % i.toString()) Renderer().Write(doc, file(unicode(fileName), 'w'))
def render(self): """ Mostly a copy of the render method in OSHAActionPlanReportDownload, but with some changes to handle the special reqs of Italy """ document = report.createDocument(self.session) ss = document.StyleSheet # Define some more custom styles ss.ParagraphStyles.append( ParagraphStyle( "RiskPriority", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=22, italic=True, colour=ss.Colours.Blue)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "MeasureField", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=18, underline=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "ITTitle", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=36, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "ITSubtitle", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=32, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "ITSubSubtitle", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=28, italic=True, bold=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "ITNormalBold", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=24, bold=True)), ParagraphPropertySet(left_indent=50, right_indent=50))) # XXX: This part is removed # self.addActionPlan(document) # XXX: and replaced with this part: t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) intro = createItalianIntro(document, self.context, self.request) toc = createSection(document, self.context, self.request, first_page_number=2) body = Section() heading = t( _("header_oira_report_download", default=u"OiRA Report: \"${title}\"", mapping=dict(title=self.session.title))) toc.append( Paragraph( ss.ParagraphStyles.Heading1, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), heading, )) if self.session.report_comment: # Add comment. #5985 normal_style = document.StyleSheet.ParagraphStyles.Normal toc.append(Paragraph(normal_style, self.session.report_comment)) toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) txt = t(_("toc_header", default=u"Contents")) p.append(character.Text(txt)) toc.append(p) headings = [ t(u"Adempimenti/rischi identificati, valutati e gestiti con misure " "obbligatorie adottate ed eventuali misure di miglioramento"), t(u"Adempimenti/rischi non pertinenti"), ] nodes = [ self.actioned_nodes, self.risk_not_present_nodes, ] for nodes, heading in zip(nodes, headings): if not nodes: continue self.addReportNodes(document, nodes, heading, toc, body) toc.append(Paragraph(LINE)) body.append(Paragraph(LINE)) document.Sections.append(body) # Until here... renderer = Renderer() output = StringIO() renderer.Write(document, output) # Custom filename filename = u"Documento di valutazione dei rischi {}".format( self.session.title) self.request.response.setHeader( "Content-Disposition", "attachment; filename=\"%s.rtf\"" % filename.encode("utf-8")) self.request.response.setHeader("Content-Type", "application/rtf") return output.getvalue()
def render(self): """ Mostly a copy of the render method in euphorie.client, but with some changes to also show unanswered risks and non-present risks. #1517 and #1518 """ document = report.createDocument(self.session) ss = document.StyleSheet # Define some more custom styles ss.ParagraphStyles.append( ParagraphStyle( "RiskPriority", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=22, italic=True, colour=ss.Colours.Blue)), ParagraphPropertySet(left_indent=300, right_indent=300))) ss.ParagraphStyles.append( ParagraphStyle( "MeasureField", TextStyle( TextPropertySet(font=ss.Fonts.Arial, size=18, underline=True)), ParagraphPropertySet(left_indent=300, right_indent=300))) # XXX: This part is removed # self.addActionPlan(document) # XXX: and replaced with this part: t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) toc = createSection(document, self.context, self.request) body = Section() heading = t( _("header_oira_report_download", default=u"OiRA Report: \"${title}\"", mapping=dict(title=self.session.title))) toc.append( Paragraph( ss.ParagraphStyles.Heading1, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), heading, )) if self.session.report_comment: # Add comment. #5985 normal_style = document.StyleSheet.ParagraphStyles.Normal toc.append(Paragraph(normal_style, self.session.report_comment)) toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) txt = t(_("toc_header", default=u"Contents")) p.append(character.Text(txt)) toc.append(p) headings = [ t( _("header_present_risks", default=u"Risks that have been identified, " u"evaluated and have an Action Plan")), t( _("header_unevaluated_risks", default=u"Risks that have been identified but " u"do NOT have an Action Plan")), t( _("header_unanswered_risks", default=u'Hazards/problems that have been "parked" ' u'and are still to be dealt with')), t( _("header_risks_not_present", default=u"Hazards/problems that have been managed " u"or are not present in your organisation")) ] nodes = [ self.actioned_nodes, self.unactioned_nodes, self.unanswered_nodes, self.risk_not_present_nodes, ] for nodes, heading in zip(nodes, headings): if not nodes: continue self.addReportNodes(document, nodes, heading, toc, body) toc.append(Paragraph(LINE)) body.append(Paragraph(LINE)) self.addConsultationBox(body, document) document.Sections.append(body) # Until here... renderer = Renderer() output = StringIO() renderer.Write(document, output) filename = translate( _("filename_report_actionplan", default=u"Action plan ${title}", mapping=dict(title=self.session.title)), context=self.request, ) self.request.response.setHeader( "Content-Disposition", "attachment; filename=\"%s.rtf\"" % filename.encode("utf-8")) self.request.response.setHeader("Content-Type", "application/rtf") return output.getvalue()