def make_pictures(): doc, section, styles = RTFTestCase.initializeDoc() # text can be added directly to the section a paragraph object is create as needed section.append( 'Image Example 1' ) section.append( 'You can add images in one of two ways, either converting the ' 'image each and every time like;' ) image = Image( 'examples/image.jpg' ) section.append( Paragraph( image ) ) section.append( 'Or you can use the image object to convert the image and then ' 'save it to a raw code element that can be included later.' ) # Test RawCode -- split into separate test? rawCodeDecl = image.ToRawCode('TEST_IMAGE') assert rawCodeDecl.startswith('TEST_IMAGE = RawCode( """') assert rawCodeDecl.endswith('""" )') rawCode = RawCode(image.Data) section.append(rawCode) section.append('The above picture was displayed from a RawCode object without a Paragraph wrapper.') section.append( 'Here are some png files' ) for f in [ 'examples/img1.png', 'examples/img2.png', 'examples/img3.png', 'examples/img4.png' ] : section.append( Paragraph( Image( f ) ) ) return doc
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 make_charFrame(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() thinEdge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE, colour=styles.Colours.Blue) textWithFrame = TextPropertySet(frame=thinEdge) p.append(Text('This tests frame drawn around text.', textWithFrame)) section.append(p) return doc
def addConsultationBox(self, section, document): """ Add the consultation box that needs to be signed by the employer and workers. """ ss = document.StyleSheet styles = document.StyleSheet.ParagraphStyles thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) table = Table(9500) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) no_edge = BorderPropertySet(width=0, colour=ss.Colours.White) p = Paragraph( styles.Heading3, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), t( _("header_oira_report_consultation", default="Consultation of workers"))) c = Cell(p, FramePropertySet(thin_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( styles.Normal, ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), t( _("paragraph_oira_consultation_of_workers", default="The undersigned hereby declare that the workers " "have been consulted on the content of this " "document.")), LINE) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( styles.Normal, ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), ) employer = t( _("oira_consultation_employer", default="On behalf of the employer:")) workers = t( _("oira_consultation_workers", default="On behalf of the workers:")) p.append(employer, TAB, TAB, TAB, TAB, workers, LINE, LINE) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), t(_("oira_survey_date", default="Date:")), LINE, LINE) c = Cell(p, FramePropertySet(no_edge, thin_edge, thin_edge, thin_edge)) table.AddRow(c) section.append(table)
def make_spaceBetweenLines(): doc, section, styles = RTFTestCase.initializeDoc() para_props = ParagraphPropertySet() quarterInch = 1440/2 para_props.SetSpaceBetweenLines(quarterInch) p = Paragraph(para_props) p.append( 'Paragraph One', LINE, 'Second line', LINE, 'Third line', ) section.append(p) para_props = ParagraphPropertySet() para_props.SetSpaceBetweenLines(-quarterInch) p = Paragraph(para_props) p.append( 'Paragraph Two', LINE, 'Second line', LINE, 'Third line', ) section.append(p) return doc
def make_paraTabs(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append( 'The paragraph itself can also be overridden in lots of ways: ' 'tabs, borders, alignment, etc., can all be modified either in ' 'the style or as an override during the creation of the ' 'paragraph. This is demonstrated below with custom tab widths ' 'and embedded carriage returns (i.e., new line markers that do ' 'not cause a paragraph break).') section.append(p) tabs = [ TabPropertySet(width=TabPropertySet.DEFAULT_WIDTH), TabPropertySet(width=TabPropertySet.DEFAULT_WIDTH * 2), TabPropertySet(width=TabPropertySet.DEFAULT_WIDTH)] para_props = ParagraphPropertySet(tabs=tabs) p = Paragraph(styles.ParagraphStyles.Normal, para_props) p.append( 'Phrase at Left Tab', TAB, 'Middle Phrase One', TAB, 'Right Phrase', LINE, 'Second Left Phrase', TAB, 'Middle Phrase Two', TAB, 'Another Right Phrase' ) section.append(p) return doc
def make_headerFooterDiffPages(): doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append(section) section.FirstHeader.append('This is the header for the first page.') section.FirstFooter.append('This is the footer for the first page.') section.Header.append( 'This is the header that will appear on subsequent pages.') section.Footer.append( 'This is the footer that will appear on subsequent pages.') p = Paragraph(ss.ParagraphStyles.Heading1) p.append('Example 6') section.append(p) # blank paragraphs are just empty strings section.append('') p = Paragraph(ss.ParagraphStyles.Normal) p.append( 'This document has different headers and footers for the first and then subsequent pages. ' 'If you insert a page break you should see a different header and footer.' ) section.append(p) return doc
def make_charTab(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append('Before tab') p.append(Text(TAB)) p.append('After tab') section.append(p) return doc
def addIdentificationResults(self, document): survey = self.request.survey section = createIdentificationReportSection( document, self.context, self.request) styles = document.StyleSheet.ParagraphStyles header_styles = { 0: styles.Heading2, 1: styles.Heading3, 2: styles.Heading4, 3: styles.Heading5, 4: styles.Heading6, } for node in self.getNodes(): section.append( Paragraph( header_styles.get(node.depth, styles.Heading6), u"%s %s" % (node.number, node.title)) ) if node.type != "risk": continue zodb_node = survey.restrictedTraverse(node.zodb_path.split("/")) section.append( Paragraph( styles.Normal, utils.html_unescape( htmllaundry.StripMarkup(zodb_node.description)) ) ) for i in range(0, 8): p = Paragraph(styles.Normal, " ") section.append(p) tabs = TabPropertySet( section.TwipsToRightMargin(), alignment=TabPropertySet.RIGHT, leader=getattr(TabPropertySet, 'UNDERLINE') ) p = Paragraph(styles.Normal, ParagraphPropertySet(tabs=[tabs])) p.append(TAB) section.append(p) if node.comment and node.comment.strip(): section.append(Paragraph(styles.Comment, node.comment))
def make_tableVerticalCellMerge(): doc, section, styles = RTFTestCase.initializeDoc() section.append('Table with Vertical Cells Merged') table = Table(TableTestCase.col1, TableTestCase.col2, TableTestCase.col3) table.AddRow(Cell('A-one'), Cell('A-two', vertical_merge=True), Cell('A-three')) table.AddRow(Cell('A-one'), Cell(vertical_merge=True), Cell('A-three')) table.AddRow(Cell('A-one'), Cell('A-two', start_vertical_merge=True), Cell('A-three')) table.AddRow(Cell('A-one'), Cell(vertical_merge=True), Cell('A-three')) table.AddRow( Cell(Paragraph( ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), 'SPREAD'), span=3)) table.AddRow(Cell('A-one'), Cell('A-two', vertical_merge=True), Cell('A-three')) table.AddRow(Cell('A-one'), Cell(vertical_merge=True), Cell('A-three')) table.AddRow(Cell('A-one'), Cell('A-two', start_vertical_merge=True), Cell('A-three')) table.AddRow(Cell('A-one'), Cell(vertical_merge=True), Cell('A-three')) section.append(table) return doc
def _makePara(name): tabs = TabPropertySet( section.TwipsToRightMargin(), alignment=TabPropertySet.RIGHT, leader=getattr(TabPropertySet, name.upper().replace(' ', '_'))) para_props = ParagraphPropertySet(tabs=[tabs]) return Paragraph(styles.ParagraphStyles.Normal, para_props)
def _WriteElements(self, elements): new_line = '' for element in elements: self._write(new_line) new_line = '\n' clss = element.__class__ if clss == Paragraph: self.WriteParagraphElement(element) elif clss == Table: self.WriteTableElement(element) elif clss == str: self.WriteParagraphElement(Paragraph(element)) elif clss in [RawCode, Image]: self.WriteRawCode(element) # elif clss == List: # self._HandleListElement(element) elif self.WriteCustomElement: self.WriteCustomElement(self, element) else: raise Exception( "Don't know how to handle elements of type %s" % clss)
def make_paraIndents(): doc, section, styles = RTFTestCase.initializeDoc() section.append( "The paragraphs below demonstrate the flexibility , the following is all at the " "same indent level and the one after it has the first line at a " "different indent to the rest. The third has the first line " "going in the other direction and is also separated by a page " "break. Note that the FirstLineIndent is defined as being the " "difference from the LeftIndent." ) creditURL = "http://www.shakespeare-online.com/plots/1kh4ps.html" section.append("(Paragraph text from %s.)" % creditURL) sampleParagraph = """The play opens one year after the death of Richard II, and King Henry is making plans for a crusade to the Holy Land to cleanse himself of the guilt he feels over the usurpation of Richard's crown. But the crusade must be postponed when Henry learns that Welsh rebels, led by Owen Glendower, have defeated and captured Mortimer. Although the brave Henry Percy, nicknamed Hotspur, has quashed much of the uprising, there is still much trouble in Scotland. King Henry has a deep admiration for Hotspur and he longs for his own son, Prince Hal, to display some of Hotspur's noble qualities. Hal is more comfortable in a tavern than on the battlefield, and he spends his days carousing with riff-raff in London. But King Henry also has his problems with the headstrong Hotspur, who refuses to turn over his prisoners to the state as he has been so ordered. Westmoreland tells King Henry that Hotspur has many of the traits of his uncle, Thomas Percy, the Earl of Worcester, and defying authority runs in the family.""" sampleParagraph = re.sub("\s+", " ", sampleParagraph) para_props = ParagraphPropertySet() para_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 3) p = Paragraph(styles.ParagraphStyles.Normal, para_props) p.append(sampleParagraph) section.append(p) para_props = ParagraphPropertySet() para_props.SetFirstLineIndent(TabPropertySet.DEFAULT_WIDTH * -2) para_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 3) p = Paragraph(styles.ParagraphStyles.Normal, para_props) p.append(sampleParagraph) section.append(p) para_props = ParagraphPropertySet() para_props.SetFirstLineIndent(TabPropertySet.DEFAULT_WIDTH) para_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH) p = Paragraph(styles.ParagraphStyles.Normal, para_props) p.append(sampleParagraph) section.append(p) return doc
def make_charStyleOverride(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append('This is a standard paragraph with the default style.') p = Paragraph() p.append('It is also possible to manully override a style. ', 'This is a change of just the font ', TEXT('size', size=48), ' an this is for just the font ', TEXT('typeface', font=styles.Fonts.Impact), '.') section.append(p) return doc
def make_paraNormal(): doc, section, styles = RTFTestCase.initializeDoc() p1 = Paragraph(styles.ParagraphStyles.Heading1) p1.append('Heading 1') section.append(p1) p2 = Paragraph(styles.ParagraphStyles.Normal) p2.append( 'In this case we have used two styles. The first paragraph is ' 'marked with the Heading1 style, and this one is marked with the ' 'Normal style.') section.append(p2) return doc
def export(self, tempdir): self.outpath = os.path.join(tempdir, 'export.rtf') self.imgnum = 1 doc = Document() self.ss = doc.StyleSheet export_title = u'Export (%d records)' % len(self.objs) on_empty_page = True if self.custom_order: emitter = self.custom_emit_fields else: emitter = self.record_emit_fields count = 0 size = len(self.objs) while len(self.objs) > 0: count += 1 yield "Formatting record %d of %d" % (count, size) r = self.objs.pop(0) if on_empty_page: section = Section() else: section = Section(break_type=Section.PAGE) on_empty_page = False p = Paragraph(self.ss.ParagraphStyles.Heading1) p.append(r.title) section.append(p) for p in self.emit_paragraphs(r, emitter(r)): section.append(p) if len(section) > 0: doc.Sections.append(section) fd = open(self.outpath, "wb") doc.write(fd) fd.close()
def add_sentences_table(self, section): global LANGS p = Paragraph( self.ss.ParagraphStyles.Heading1 ) p.append(TEXT('Example Sentences ({0})'.format(LANGS[self.lang]),bold=True)) section.append( p ) table = Table(TabPropertySet.DEFAULT_WIDTH * 1, TabPropertySet.DEFAULT_WIDTH * 9, TabPropertySet.DEFAULT_WIDTH * 3) thin_edge = BorderPropertySet( width=10, style=BorderPropertySet.SINGLE ) thick_edge = BorderPropertySet( width=80, style=BorderPropertySet.SINGLE ) thin_frame = FramePropertySet( thin_edge, thin_edge, thin_edge, thin_edge ) thick_frame = FramePropertySet( thick_edge, thick_edge, thick_edge, thick_edge ) mixed_frame = FramePropertySet( thin_edge, thick_edge, thin_edge, thick_edge ) h1 = self.cell("CM#",True) h2 = self.cell("Sentence",True) h3 = self.cell("Fragment",True) table.AddRow(h1,h2,h3) for (id, sent, frag, trans) in sorted(self.sentences,key=lambda key: float(key[0])): color=None # if there is a previous log, color new things red if self.plog: color=self.ss.Colours.Red if 'sentences' in self.plog: for (lid, lsent, lfrag) in self.plog['sentences']: if (rtf_encode(id)==lid) and (rtf_encode(sent)==lsent) and (rtf_encode(frag)==lfrag): color=None break c1 = self.cell(id, False, color) c2 = self.cell(sent, False, color) c3 = self.cell(frag, False, color) table.AddRow(c1,c2,c3) # put sentence translation on next line for non-EN and if trans is present if (self.lang != "en") and trans: c1 = self.cell("", False, color) c2 = self.cell(trans, False, color) c3 = self.cell("", False, color) table.AddRow(c1,c2,c3) section.append(table)
def make_charUnicode(): doc, section, styles = RTFTestCase.initializeDoc() section.append('This tests unicode.') p = Paragraph() p.append('32\u00B0 Fahrenheit is 0\u00B0 Celsuis') section.append(p) p = Paragraph() p.append('Henry \u2163 is Henry IV in unicode.') section.append(p) return doc
def make_charInline(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append(Inline('Simple Inline Element')) section.append(p) # Test various element types inside Inline element. p = Paragraph() p.append( Inline('First Inline Element', TAB, 'Second Inline Element', RawCode(r'\tab '), 'After tab')) section.append(p) return doc
def add_subdimensions_table(self, section): global LANGS p = Paragraph( self.ss.ParagraphStyles.Heading1 ) p.append(TEXT('Proposed Common Program Sources and Source Sub-dimensions ({0})'.format(LANGS[self.lang]),bold=True)) section.append( p ) table = Table(TabPropertySet.DEFAULT_WIDTH * 1, TabPropertySet.DEFAULT_WIDTH * 2, TabPropertySet.DEFAULT_WIDTH * 3, TabPropertySet.DEFAULT_WIDTH * 4, TabPropertySet.DEFAULT_WIDTH * 3 ) h1 = self.cell("CM#",True) h2 = self.cell("Target",True) h3 = self.cell("Semantic Clusters",True) h4 = self.cell("Source Sub-dimensions",True) h5 = self.cell("Source",True) table.AddRow(h1,h2,h3,h4,h5) for id in sorted(self.subdimensions, key=lambda key: float(key)): color=None # if there is a previous log, color new things red if self.plog: color=self.ss.Colours.Red if 'subdimensions' in self.plog: if id in self.plog['subdimensions']: color=None c1 = self.cell(id,False,color) c2 = self.cell(self.subdimensions[id][0],False,color) c3 = self.cell(self.subdimensions[id][1],False,color) c4 = self.cell(self.subdimensions[id][2],False,color) c5 = self.cell(self.subdimensions[id][3],False,color) table.AddRow(c1,c2,c3,c4,c5) if (self.lang=='fa') and (id in self.subdim_glosses): t1 = self.cell('',False,color) t2 = self.cell(self.subdim_glosses[id][0],False,color) t3 = self.cell(self.subdim_glosses[id][1],False,color) t4 = self.cell(self.subdim_glosses[id][2],False,color) t5 = self.cell(self.subdim_glosses[id][3],False,color) table.AddRow(t1,t2,t3,t4,t5) section.append(table)
def make_paraTabs(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append( "The paragraph itself can also be overridden in lots of ways: " "tabs, borders, alignment, etc., can all be modified either in " "the style or as an override during the creation of the " "paragraph. This is demonstrated below with custom tab widths " "and embedded carriage returns (i.e., new line markers that do " "not cause a paragraph break)." ) section.append(p) tabs = [ TabPropertySet(width=TabPropertySet.DEFAULT_WIDTH), TabPropertySet(width=TabPropertySet.DEFAULT_WIDTH * 2), TabPropertySet(width=TabPropertySet.DEFAULT_WIDTH), ] para_props = ParagraphPropertySet(tabs=tabs) p = Paragraph(styles.ParagraphStyles.Normal, para_props) p.append( "Phrase at Left Tab", TAB, "Middle Phrase One", TAB, "Right Phrase", LINE, "Second Left Phrase", TAB, "Middle Phrase Two", TAB, "Another Right Phrase", ) section.append(p) return doc
def make_headerFooterDiffPages(): doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) section.FirstHeader.append( 'This is the header for the first page.' ) section.FirstFooter.append( 'This is the footer for the first page.' ) section.Header.append( 'This is the header that will appear on subsequent pages.' ) section.Footer.append( 'This is the footer that will appear on subsequent pages.' ) p = Paragraph( ss.ParagraphStyles.Heading1 ) p.append( 'Example 6' ) section.append( p ) # blank paragraphs are just empty strings section.append( '' ) p = Paragraph( ss.ParagraphStyles.Normal ) p.append( 'This document has different headers and footers for the first and then subsequent pages. ' 'If you insert a page break you should see a different header and footer.' ) section.append( p ) return doc
def make_paraDefaultPreviousStyle(): doc, section, styles = RTFTestCase.initializeDoc() p1 = Paragraph(styles.ParagraphStyles.Heading1) p1.append('Heading 1') section.append(p1) p2 = Paragraph(styles.ParagraphStyles.Normal) p2.append( 'In this case we have used two styles. The first paragraph is ' 'marked with the Heading1 style, and this one is marked with the ' 'Normal style.') section.append(p2) p3 = Paragraph() p3.append( 'Notice that after changing the style of the paragraph to Normal ' '(in the previous paragraph), all subsequent paragraphs have ' 'that style automatically. This saves typing and is actually the ' 'default native behaviour for RTF documents.') section.append(p3) return doc
def test_paraAsList(self): text1 = "First line" text2 = "Second line" text3 = "Third line" # Build paragraph using constructor. p1 = Paragraph(text1, text2, text3) # Build paragraph using append. p2 = Paragraph() p2.append(text1) p2.append(text2) p2.append(text3) # Build paragraph using insert. p3 = Paragraph() p3.insert(0, text1) p3.insert(1, text2) p3.insert(2, text3) # Confirm contents are same. assert p1[0:-1] == p2[0:-1] assert p2[0:-1] == p3[0:-1]
def createIdentificationReportSection(document, survey, request): t = lambda txt: "".join( ["\u%s?" % str(ord(e)) for e in translate(txt, context=request)]) section = Section() footer_txt = t( _("report_identification_revision", default=u"This document was based on the OiRA Tool '${title}' of " u"revision date ${date}.", mapping={ "title": survey.published[1], "date": formatDate(request, survey.published[2]) })) header = Table(4750, 4750) c1 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, SessionManager.session.title)) pp = ParagraphPropertySet header_props = pp(alignment=pp.RIGHT) c2 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, header_props, formatDate(request, datetime.today()))) header.AddRow(c1, c2) section.Header.append(header) footer = Table(9000, 500) c1 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, pp(alignment=pp.LEFT), footer_txt)) c2 = Cell(Paragraph(pp(alignment=pp.RIGHT), PAGE_NUMBER)) footer.AddRow(c1, c2) section.Footer.append(footer) section.SetBreakType(section.PAGE) document.Sections.append(section) return section
def addConsultationBox(self, section, document): """ Add the consultation box that needs to be signed by the employer and workers. """ ss = document.StyleSheet styles = document.StyleSheet.ParagraphStyles thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) t = lambda txt: "".join([ "\u%s?" % str(ord(e)) for e in translate(txt, context=self.request) ]) table = Table(9500) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) no_edge = BorderPropertySet(width=0, colour=ss.Colours.White) p = Paragraph( styles.Heading3, ParagraphPropertySet(alignment=ParagraphPropertySet.CENTER), t(_("header_oira_report_consultation", default="Consultation of workers")) ) c = Cell(p, FramePropertySet(thin_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( styles.Normal, ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), t(_("paragraph_oira_consultation_of_workers", default="The undersigned hereby declare that the workers " "have been consulted on the content of this " "document.")), LINE ) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( styles.Normal, ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), ) employer = t(_("oira_consultation_employer", default="On behalf of the employer:")) workers = t(_("oira_consultation_workers", default="On behalf of the workers:")) p.append(employer, TAB, TAB, TAB, TAB, workers, LINE, LINE) c = Cell(p, FramePropertySet(no_edge, thin_edge, no_edge, thin_edge)) table.AddRow(c) p = Paragraph( ParagraphPropertySet(alignment=ParagraphPropertySet.LEFT), t(_("oira_survey_date", default="Date:")), LINE, LINE ) c = Cell(p, FramePropertySet(no_edge, thin_edge, thin_edge, thin_edge)) table.AddRow(c) section.append(table)
def createSection(document, survey, request, first_page_number=1): t = lambda txt: "".join( ["\u%s?" % str(ord(e)) for e in translate(txt, context=request)]) section = Section(break_type=Section.PAGE, first_page_number=first_page_number) footer_txt = t( _("report_survey_revision", default=u"This report was based on the OiRA Tool '${title}' "\ u"of revision date ${date}.", mapping={"title": survey.published[1], "date": formatDate(request, survey.published[2])})) header = Table(4750, 4750) c1 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, survey.published[1])) pp = ParagraphPropertySet header_props = pp(alignment=pp.RIGHT) c2 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, header_props, formatDate(request, datetime.today()))) header.AddRow(c1, c2) section.Header.append(header) footer = Table(9000, 500) # rtfng does not like unicode footers c1 = Cell( Paragraph(document.StyleSheet.ParagraphStyles.Footer, pp(alignment=pp.LEFT), footer_txt)) c2 = Cell(Paragraph(pp(alignment=pp.RIGHT), PAGE_NUMBER)) footer.AddRow(c1, c2) section.Footer.append(footer) document.Sections.append(section) return section
def make_hyperlinks(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append('This is a standard paragraph with the default style.') p = Paragraph() p.append('This is also a standard paragraph. ', 'But lets add a ', TEXT('Washington Post', hyperlink='https://washingtonpost.com'), ' hyperlink to this paragraph. ', ) section.append(p) return doc
def make_charStyleOverride(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append('This is a standard paragraph with the default style.') p = Paragraph() p.append('It is also possible to manully override a style. ', 'This is a change of just the font ', TEXT('size', size=48), ' an this is for just the font ', TEXT('typeface', font=styles.Fonts.Impact) , '.') section.append(p) return doc
def make_headerFooterSimple(): doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append(section) section.Header.append('This is the header') section.Footer.append('This is the footer') p = Paragraph(ss.ParagraphStyles.Heading1) p.append('Example 5') section.append(p) # blank paragraphs are just empty strings section.append('') p = Paragraph(ss.ParagraphStyles.Normal) p.append('This document has a header and a footer.') section.append(p) return doc
def make_charUnicode(): doc, section, styles = RTFTestCase.initializeDoc() section.append('This tests unicode.') p = Paragraph() p.append(u'32\u00B0 Fahrenheit is 0\u00B0 Celsuis') section.append(p) p = Paragraph() p.append(u'Henry \u2163 is Henry IV in unicode.') section.append(p) return doc
def make_charInline(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph() p.append(Inline('Simple Inline Element')) section.append(p) # Test various element types inside Inline element. p = Paragraph() p.append(Inline('First Inline Element', TAB, 'Second Inline Element', RawCode(r'\tab '), 'After tab' )) section.append(p) return doc
def make_spaceBetweenLines(): doc, section, styles = RTFTestCase.initializeDoc() para_props = ParagraphPropertySet() quarterInch = 1440 / 2 para_props.SetSpaceBetweenLines(quarterInch) p = Paragraph(para_props) p.append("Paragraph One", LINE, "Second line", LINE, "Third line") section.append(p) para_props = ParagraphPropertySet() para_props.SetSpaceBetweenLines(-quarterInch) p = Paragraph(para_props) p.append("Paragraph Two", LINE, "Second line", LINE, "Third line") section.append(p) return doc
def make_headerFooterSimple(): doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append( section ) section.Header.append( 'This is the header' ) section.Footer.append( 'This is the footer' ) p = Paragraph( ss.ParagraphStyles.Heading1 ) p.append( 'Example 5' ) section.append( p ) # blank paragraphs are just empty strings section.append( '' ) p = Paragraph( ss.ParagraphStyles.Normal ) p.append( 'This document has a header and a footer.' ) section.append( p ) return doc
def WriteTableElement(self, table_elem): vmerge = [False] * table_elem.ColumnCount for height, cells in table_elem.Rows: # calculate the right hand edge of the cells taking into account the spans offset = table_elem.LeftOffset or 0 cellx = [] cell_idx = 0 for cell in cells: cellx.append(offset + sum(table_elem.ColumnWidths[:cell_idx + cell.Span])) cell_idx += cell.Span self._write(r'{\trowd') settings = Settings() # the spec says that this value is mandatory and I think that 108 is the default value # so I'll take care of it here settings.append(table_elem.GapBetweenCells or 108, 'trgaph%s') settings.append(TableAlignmentMap[table_elem.Alignment]) settings.append(height, 'trrh%s') settings.append(table_elem.LeftOffset, 'trleft%s') width = table_elem.LeftOffset or 0 for idx, cell in enumerate(cells): self._RendFramePropertySet(cell.Frame, settings, 'cl') # cells don't have margins so I don't know why I was doing this # I think it might have an affect in some versions of some WPs. #self._RendMarginsPropertySet(cell.Margins, settings, 'cl') # if we are starting to merge or if this one is the first in what is # probably a series of merges then start the vertical merging if cell.StartVerticalMerge or (cell.VerticalMerge and not vmerge[idx]): settings.append('clvmgf') vmerge[idx] = True elif cell.VerticalMerge: # ..continuing a merge settings.append('clvmrg') else: # ..no merging going on so make sure that it is off vmerge[idx] = False # for any cell in the next row that is covered by this span we # need to run off the vertical merging as we don't want them # merging up into this spanned cell for vmerge_idx in range(idx + 1, idx + cell.Span - 1): vmerge[vmerge_idx] = False settings.append(CellAlignmentMap[cell.Alignment]) settings.append(CellFlowMap[cell.Flow]) # this terminates the definition of a cell and represents the right most edge of the cell from the left margin settings.append(cellx[idx], 'cellx%s') self._write(repr(settings)) for cell in cells: if len(cell): last_idx = len(cell) - 1 for element_idx, element in enumerate(cell): # wrap plain strings in paragraph tags if isinstance(element, str): element = Paragraph(element) # don't forget the prefix or else word crashes and does all sorts of strange things if element_idx == last_idx: self.WriteParagraphElement(element, tag_prefix=r'\intbl', tag_suffix='', opening='', closing='') else: self.WriteParagraphElement(element, tag_prefix=r'\intbl', opening='', closing='') self._write(r'\cell') else: self._write(r'\pard\intbl\cell') self._write('\\row}\n')
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()
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 new_title(self, text, level=1): style = getattr(self.ss.ParagraphStyles, "Heading%d" % level) p = Paragraph(style) p.append(text) return p
def addReportNodes(self, document, nodes, heading, toc, body): """ """ t = lambda txt: "".join(["\u%s?" % str(ord(e)) for e in translate(txt, context=self.request)]) ss = document.StyleSheet toc_props = ParagraphPropertySet() toc_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 1) toc_props.SetRightIndent(TabPropertySet.DEFAULT_WIDTH * 1) p = Paragraph(ss.ParagraphStyles.Heading6, toc_props) p.append(character.Text(heading, TextPropertySet(italic=True))) toc.append(p) body.append(Paragraph(ss.ParagraphStyles.Heading1, heading)) survey = self.request.survey styles = ss.ParagraphStyles header_styles = { 0: styles.Heading2, 1: styles.Heading3, 2: styles.Heading4, 3: styles.Heading5, 4: styles.Heading6, } for node in nodes: zodb_node = survey.restrictedTraverse(node.zodb_path.split("/")) title = node_title(node, zodb_node) thin_edge = BorderPropertySet(width=20, style=BorderPropertySet.SINGLE) if node.depth == 1: p = Paragraph( header_styles.get(node.depth, styles.Heading6), FramePropertySet(thin_edge, thin_edge, thin_edge, thin_edge), u"%s %s" % (node.number, title), ) else: p = Paragraph(header_styles.get(node.depth, styles.Heading6), u"%s %s" % (node.number, title)) body.append(p) if node.type != "risk": continue if node.priority: if node.priority == "low": level = _("risk_priority_low", default=u"low") elif node.priority == "medium": level = _("risk_priority_medium", default=u"medium") elif node.priority == "high": level = _("risk_priority_high", default=u"high") msg = _( "risk_priority", default="This is a ${priority_value} priority risk.", mapping={"priority_value": level}, ) body.append(Paragraph(styles.RiskPriority, t(msg))) if getattr(node, "identification", None) == "no": body.append( Paragraph( styles.Normal, ParagraphPropertySet(left_indent=300, right_indent=300), t(_(utils.html_unescape(htmllaundry.StripMarkup(zodb_node.description)))), ) ) body.append(Paragraph("")) if node.comment and node.comment.strip(): body.append(Paragraph(styles.Comment, node.comment)) for (idx, measure) in enumerate(node.action_plans): if not measure.action_plan: continue if len(node.action_plans) == 1: heading = t(_("header_measure_single", default=u"Measure")) else: heading = t(_("header_measure", default=u"Measure ${index}", mapping={"index": idx + 1})) self.addMeasure(document, heading, body, measure)
def cell(self,text,bold=False,color=None): return Cell(Paragraph(self.ss.ParagraphStyles.Normal, TEXT(rtf_encode(text),bold=bold,colour=color)), self.thin_frame)
def make_paraHeading(): doc, section, styles = RTFTestCase.initializeDoc() p1 = Paragraph(styles.ParagraphStyles.Heading1) p1.append("Heading 1") section.append(p1) return doc
def append_text_field(self, field): block_elts = set('h1,h2,h3,h4,h5,h6,div,p,br'.split(',')) para = None formatting_stack = [TextPropertySet()] for action, elt in etree.iterwalk(field.get_elt(), events=("start", "end")): closing = (action == 'end') is_block = (elt.tag in block_elts) if closing: if elt.tag in ('b', 'i', 'u'): formatting_stack.pop() else: if elt.tag in ('b', 'i', 'u'): new_format = formatting_stack[-1].Copy() if elt.tag == 'b': new_format.bold = True elif elt.tag == 'i': new_format.italic = True elif elt.tag == 'u': new_format.underline = True formatting_stack.append(new_format) if para is not None and is_block: # If starting or ending a block tag, and have some text # buffered, emit it. yield para para = None textprops = formatting_stack[-1] # Add any trailing text for closing tags. if closing: if elt.tail: if para is None: para = Paragraph(self.ss.ParagraphStyles.Normal) para.append(Text(self.encode_unicode(elt.tail), textprops)) continue # Handle special element types. if elt.tag == 'br': assert para is None para = Paragraph(self.ss.ParagraphStyles.Normal) #para.append(LINE) continue data_type = elt.attrib.get('data-type', None) display = elt.attrib.get('data-display', None) if data_type == 'file': src = elt.attrib.get('data-src', None) mimetype = elt.attrib.get('data-mimetype', None) alt = elt.attrib.get('data-alt', None) title = elt.attrib.get('data-title', None) if para is None: para = Paragraph(self.ss.ParagraphStyles.Normal) self.append_file(para, mimetype, src, title or alt) continue elif data_type == 'link': linktype = elt.attrib.get('data-linktype', '') if linktype == 'file': src = elt.attrib.get('data-target', None) mimetype = elt.attrib.get('data-mimetype', None) if mimetype.startswith('image/'): alt = elt.attrib.get('data-alt', None) title = elt.attrib.get('data-title', None) if para is None: para = Paragraph(self.ss.ParagraphStyles.Normal) self.append_file(para, mimetype, src, title or alt) continue if elt.text: if para is None: para = Paragraph(self.ss.ParagraphStyles.Normal) para.append(Text(self.encode_unicode(elt.text), textprops)) if para is not None: yield para
def make_paraIndents(): doc, section, styles = RTFTestCase.initializeDoc() section.append( 'The paragraphs below demonstrate the flexibility , the following is all at the ' 'same indent level and the one after it has the first line at a ' 'different indent to the rest. The third has the first line ' 'going in the other direction and is also separated by a page ' 'break. Note that the FirstLineIndent is defined as being the ' 'difference from the LeftIndent.') creditURL = 'http://www.shakespeare-online.com/plots/1kh4ps.html' section.append('(Paragraph text from %s.)' % creditURL) sampleParagraph = """The play opens one year after the death of Richard II, and King Henry is making plans for a crusade to the Holy Land to cleanse himself of the guilt he feels over the usurpation of Richard's crown. But the crusade must be postponed when Henry learns that Welsh rebels, led by Owen Glendower, have defeated and captured Mortimer. Although the brave Henry Percy, nicknamed Hotspur, has quashed much of the uprising, there is still much trouble in Scotland. King Henry has a deep admiration for Hotspur and he longs for his own son, Prince Hal, to display some of Hotspur's noble qualities. Hal is more comfortable in a tavern than on the battlefield, and he spends his days carousing with riff-raff in London. But King Henry also has his problems with the headstrong Hotspur, who refuses to turn over his prisoners to the state as he has been so ordered. Westmoreland tells King Henry that Hotspur has many of the traits of his uncle, Thomas Percy, the Earl of Worcester, and defying authority runs in the family.""" sampleParagraph = re.sub('\s+', ' ', sampleParagraph) para_props = ParagraphPropertySet() para_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 3) p = Paragraph(styles.ParagraphStyles.Normal, para_props) p.append(sampleParagraph) section.append(p) para_props = ParagraphPropertySet() para_props.SetFirstLineIndent(TabPropertySet.DEFAULT_WIDTH * -2) para_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH * 3) p = Paragraph(styles.ParagraphStyles.Normal, para_props) p.append(sampleParagraph) section.append(p) para_props = ParagraphPropertySet() para_props.SetFirstLineIndent(TabPropertySet.DEFAULT_WIDTH) para_props.SetLeftIndent(TabPropertySet.DEFAULT_WIDTH) p = Paragraph(styles.ParagraphStyles.Normal, para_props) p.append(sampleParagraph) section.append(p) return doc
ss.ParagraphStyles.append(ps) ps = ParagraphStyle('Header', TextStyle(TextPropertySet(ss.Fonts.Arial, 16)).Copy(), ParagraphPropertySet(left_indent=int((9.0/16.0)*1440), space_before=0, space_after=60)) ss.ParagraphStyles.append(ps) ps = ParagraphStyle('Footer', TextStyle(TextPropertySet(ss.Fonts.Arial, 16)).Copy(), ParagraphPropertySet(space_before=60, tabs=[\ TabPropertySet(int(0.5*section.TwipsToRightMargin()), alignment=TabPropertySet.CENTER), TabPropertySet(int(0.5*section.TwipsToRightMargin()), alignment=TabPropertySet.RIGHT)])) ss.ParagraphStyles.append(ps) # Put in the header and footer p = Paragraph(ss.ParagraphStyles.Header) p.append("Program Director/Principal Investigator (Last, First, Middle): ") section.Header.append(p) p = Paragraph(ss.ParagraphStyles.Footer, top_frame) p.append('PHS 398/2590 (Rev. 06/09)', TAB, 'Page ', PAGE_NUMBER, TAB, "Biographical Sketch Format Page") section.Footer.append(p) # Put in the top table table = Table(5310, 270, 1170, 1440, 2610) p1 = Paragraph(ss.ParagraphStyles.Title, "BIOGRAPHICAL SKETCH") p2 = Paragraph(ss.ParagraphStyles.Subtitle) p2.append('Provide the following information for the Senior/key personnel ' \
ParagraphPropertySet(space_before=60, space_after=60)) ss.ParagraphStyles.append(ps) ps = ParagraphStyle('Heading 3', TextStyle(TextPropertySet(ss.Fonts.Arial, 22)).Copy(), ParagraphPropertySet(space_before=60, space_after=60)) ss.ParagraphStyles.append(ps) ps = ParagraphStyle('Heading 4', TextStyle(TextPropertySet(ss.Fonts.Arial, 22)).Copy(), ParagraphPropertySet(space_before=60, space_after=60)) ss.ParagraphStyles.append(ps) section = Section() doc.Sections.append(section) section.FirstHeader.append(' ') p = Paragraph(ss.ParagraphStyles.Normal) p.append(PAGE_NUMBER, ' of ', TOTAL_PAGES) section.FirstFooter.append(p) section.Header.append(report_title) p = Paragraph(ss.ParagraphStyles.Normal) p.append(PAGE_NUMBER, ' of ', TOTAL_PAGES) section.Footer.append(p) p = Paragraph(ss.ParagraphStyles.Title) p.append(report_title) section.append(p) for row in csvReader: n = n + 1
def make_paraHeading(): doc, section, styles = RTFTestCase.initializeDoc() p1 = Paragraph(styles.ParagraphStyles.Heading1) p1.append('Heading 1') section.append(p1) return doc
def make_headerFooterDiffPagesAndSections(): doc = Document() ss = doc.StyleSheet section = Section() doc.Sections.append(section) section.FirstHeader.append('This is the header for the first page.') section.FirstFooter.append('This is the footer for the first page.') section.Header.append( 'This is the header that will appear on subsequent pages.') section.Footer.append( 'This is the footer that will appear on subsequent pages.') p = Paragraph(ss.ParagraphStyles.Heading1) p.append('Example 7') section.append(p) p = Paragraph(ss.ParagraphStyles.Normal) p.append( 'This document has different headers and footers for the first and then subsequent pages. ' 'If you insert a page break you should see a different header and footer.' ) section.append(p) p = Paragraph(ss.ParagraphStyles.Normal, ParagraphPropertySet().SetPageBreakBefore(True)) p.append('This should be page 2 ' 'with the subsequent headers and footers.') section.append(p) section = Section(break_type=Section.PAGE, first_page_number=1) doc.Sections.append(section) section.FirstHeader.append( 'This is the header for the first page of the second section.') section.FirstFooter.append( 'This is the footer for the first page of the second section.') section.Header.append( 'This is the header that will appear on subsequent pages for the second section.' ) p = Paragraph( 'This is the footer that will appear on subsequent pages for the second section.', LINE) p.append(PAGE_NUMBER, ' of ', SECTION_PAGES) section.Footer.append(p) section.append('This is the first page') p = Paragraph(ParagraphPropertySet().SetPageBreakBefore(True), 'This is the second page') section.append(p) return doc
def createOrderForm(cart, member_details): """Creates and returns an order form pdf.""" member_name = unicode(member_details.get('member_name')) # member_email = unicode(member_details.get('member_email')) member_phone = unicode(member_details.get('member_phone')) # order_comments = unicode(member_details.get('order_comments')) ss = makeReportStylesheet() doc = Document(ss, default_language=Languages.EnglishUK) paper = Paper('A4', 9, 'A4 297 x 210 mm', 16838, 11907) section = Section(margins=MarginsPropertySet(top=100, left=400, bottom=100, right=400), paper=paper, landscape=True, headery=0, footery=300) doc.Sections.append(section) footer_text = member_name + " " + member_phone footer_p = Paragraph(ss.ParagraphStyles.Heading1) footer_p.append(unicode(footer_text)) section.Footer.append(footer_p) thin_edge = BorderPropertySet(width=10, style=BorderPropertySet.SINGLE) thin_frame = FramePropertySet(thin_edge, thin_edge, thin_edge, thin_edge) # based on twirps or 567/cm. table = Table(567, 3118, 709) # header header_props = ParagraphPropertySet(alignment=3) c2_para = Paragraph(ss.ParagraphStyles.Normal, header_props) c2_para.append(u'No.') c2 = Cell(c2_para, thin_frame) c3_para = Paragraph(ss.ParagraphStyles.Normal, header_props) c3_para.append(u'Product') c3 = Cell(c3_para, thin_frame) c4_para = Paragraph(ss.ParagraphStyles.Normal, header_props) c4_para.append(u'Cost') c4 = Cell(c4_para, thin_frame) table.AddRow(c2, c3, c4) # list for cart_item in cart.cartitem_set.all().order_by('product__picking_order', 'product__aisle', 'product__sort_name'): centre_props = ParagraphPropertySet(alignment=3) c2_para = Paragraph(centre_props) if cart_item.cart_bundle: c2_para.append(u"PnM") else: c2_para.append(unicode(cart_item.quantity)) c2 = Cell(c2_para, thin_frame) c3_para = Paragraph(ss.ParagraphStyles.Normal) c3_para.append(unicode(cart_item.product.order_name)) if cart_item.product.bundle: c3_para.append(u": ") for bundle_item in cart_item.cart_bundle.cartitem_set.all(): c3_para.append(unicode(bundle_item.product.order_name)) c3_para.append(u" x " + unicode(bundle_item.quantity) + u", ") c3 = Cell(c3_para, thin_frame) cost_props = ParagraphPropertySet(alignment=2) c4_para = Paragraph(cost_props) c4_para.append(unicode(cart_item.line_total)) c4 = Cell(c4_para, thin_frame) table.AddRow(c2, c3, c4) # table footer c1_para = Paragraph(ss.ParagraphStyles.Heading2Short, ParagraphPropertySet(alignment=2)) c1_para.append(u'Total cost') c1 = Cell(c1_para, thin_frame, span=2) c2_para = Paragraph(ParagraphPropertySet(alignment=2)) c2_para.append(unicode(cart.total)) c2 = Cell(c2_para, thin_frame) table.AddRow(c1, c2) # write ins for writein_item in cart.cartwriteinitem_set.all(): centre_props = ParagraphPropertySet(alignment=3) c2_para = Paragraph(centre_props) # c2_para.append(unicode(cart_item.quantity)) c2 = Cell(c2_para, thin_frame) c3_para = Paragraph(ss.ParagraphStyles.Normal) c3_para.append(u"{0} -- {1}".format(unicode(writein_item.name), unicode(writein_item.code))) c3 = Cell(c3_para, thin_frame) cost_props = ParagraphPropertySet(alignment=2) c4_para = Paragraph(cost_props) # c4_para.append(unicode(cart_item.line_total)) c4 = Cell(c4_para, thin_frame) table.AddRow(c2, c3, c4) # virtual shop items. for virtualshop_item in cart.cartvirtualshopitem_set.all(): centre_props = ParagraphPropertySet(alignment=3) c2_para = Paragraph(centre_props) c2_para.append(unicode(virtualshop_item.quantity)) c2 = Cell(c2_para, thin_frame) c3_para = Paragraph(ss.ParagraphStyles.Normal) c3_para.append(unicode(virtualshop_item.name) + u" -- VS") c3 = Cell(c3_para, thin_frame) cost_props = ParagraphPropertySet(alignment=2) c4_para = Paragraph(cost_props) # c4_para.append(unicode(cart_item.line_total)) c4 = Cell(c4_para, thin_frame) table.AddRow(c2, c3, c4) section.append(table) section.append(Paragraph()) rtf_doc = StringIO() document_renderer = Renderer() document_renderer.Write(doc, rtf_doc) return rtf_doc
def addIdentificationResults(self, document): survey = self.request.survey section = createIdentificationReportSection( document, self.context, self.request) lang = getattr(self.request, 'LANGUAGE', 'en') if "-" in lang: elems = lang.split("-") lang = "{0}_{1}".format(elems[0], elems[1].upper()) styles = document.StyleSheet.ParagraphStyles normal_style = document.StyleSheet.ParagraphStyles.Normal header_styles = { 0: styles.Heading2, 1: styles.Heading3, 2: styles.Heading4, 3: styles.Heading5, 4: styles.Heading6, } for node in self.getNodes(): section.append( Paragraph( header_styles.get(node.depth, styles.Heading6), u"%s %s" % (node.number, node.title)) ) if node.type != "risk": continue description = legal_reference = None if not getattr(node, 'is_custom_node', None): zope_node = survey.restrictedTraverse( node.zodb_path.split("/"), None) if zope_node is not None: description = getattr(zope_node, "description", None) legal_reference = getattr(zope_node, "legal_reference", None) if description and description.strip(): for el in report.HtmlToRtf(description, normal_style): section.append(el) if legal_reference and legal_reference.strip(): p = Paragraph(styles.Normal, "") section.append(p) section.append( Paragraph( styles.LegalHeading, translate(_( 'header_legal_references', default=u'Legal and policy references'), target_language=lang), ) ) p = Paragraph(styles.Normal, "") section.append(p) for el in report.HtmlToRtf(legal_reference, normal_style): section.append(el) tabs = TabPropertySet( section.TwipsToRightMargin(), alignment=TabPropertySet.RIGHT, leader=getattr(TabPropertySet, 'UNDERLINE') ) p = Paragraph(styles.Normal, ParagraphPropertySet(tabs=[tabs])) p.append(TAB) section.append(p) if node.comment and node.comment.strip(): section.append(Paragraph(styles.Comment, node.comment))
def new_para(self, section, style=None): p = Paragraph(style or self.ss.ParagraphStyles.Normal) section.append(p) return p
def make_tables(): doc, section, styles = RTFTestCase.initializeDoc() p = Paragraph( styles.ParagraphStyles.Heading1 ) p.append( 'Example 3' ) section.append( p ) # changes what is now the default style of Heading1 back to Normal p = Paragraph( styles.ParagraphStyles.Normal ) p.append( 'Example 3 demonstrates tables, tables represent one of the ' 'harder things to control in RTF as they offer alot of ' 'flexibility in formatting and layout.' ) section.append( p ) section.append( 'Table columns are specified in widths, the following example ' 'consists of a table with 3 columns, the first column is ' '7 tab widths wide, the next two are 3 tab widths wide. ' 'The widths chosen are arbitrary, they do not have to be ' 'multiples of tab widths.' ) table = Table( TabPropertySet.DEFAULT_WIDTH * 7, TabPropertySet.DEFAULT_WIDTH * 3, TabPropertySet.DEFAULT_WIDTH * 3 ) c1 = Cell( Paragraph( 'Row One, Cell One' ) ) c2 = Cell( Paragraph( 'Row One, Cell Two' ) ) c3 = Cell( Paragraph( 'Row One, Cell Three' ) ) table.AddRow( c1, c2, c3 ) c1 = Cell( Paragraph( styles.ParagraphStyles.Heading2, 'Heading2 Style' ) ) c2 = Cell( Paragraph( styles.ParagraphStyles.Normal, 'Back to Normal Style' ) ) c3 = Cell( Paragraph( 'More Normal Style' ) ) table.AddRow( c1, c2, c3 ) c1 = Cell( Paragraph( styles.ParagraphStyles.Heading2, 'Heading2 Style' ) ) c2 = Cell( Paragraph( styles.ParagraphStyles.Normal, 'Back to Normal Style' ) ) c3 = Cell( Paragraph( 'More Normal Style' ) ) table.AddRow( c1, c2, c3 ) section.append( table ) section.append( 'Different frames can also be specified for each cell in the table ' 'and each frame can have a different width and style for each border.' ) thin_edge = BorderPropertySet( width=20, style=BorderPropertySet.SINGLE ) thick_edge = BorderPropertySet( width=80, style=BorderPropertySet.SINGLE ) thin_frame = FramePropertySet( thin_edge, thin_edge, thin_edge, thin_edge ) thick_frame = FramePropertySet( thick_edge, thick_edge, thick_edge, thick_edge ) mixed_frame = FramePropertySet( thin_edge, thick_edge, thin_edge, thick_edge ) table = Table( TabPropertySet.DEFAULT_WIDTH * 3, TabPropertySet.DEFAULT_WIDTH * 3, TabPropertySet.DEFAULT_WIDTH * 3 ) c1 = Cell( Paragraph( 'R1C1' ), thin_frame ) c2 = Cell( Paragraph( 'R1C2' ) ) c3 = Cell( Paragraph( 'R1C3' ), thick_frame ) table.AddRow( c1, c2, c3 ) c1 = Cell( Paragraph( 'R2C1' ) ) c2 = Cell( Paragraph( 'R2C2' ) ) c3 = Cell( Paragraph( 'R2C3' ) ) table.AddRow( c1, c2, c3 ) c1 = Cell( Paragraph( 'R3C1' ), mixed_frame ) c2 = Cell( Paragraph( 'R3C2' ) ) c3 = Cell( Paragraph( 'R3C3' ), mixed_frame ) table.AddRow( c1, c2, c3 ) section.append( table ) section.append( 'In fact frames can be applied to paragraphs too, not just cells.' ) p = Paragraph( styles.ParagraphStyles.Normal, thin_frame ) p.append( 'This whole paragraph is in a frame.' ) section.append( p ) return doc
def make_charColours(): doc, section, styles = RTFTestCase.initializeDoc() section.append('This example test changing the colour of fonts.') # Text properties can be specified in two ways, either a text object # can have its text properties specified via the TextPropertySet # object, or by passing the colour parameter as a style. red = TextPropertySet(colour=styles.Colours.Red) green = TextPropertySet(colour=styles.Colours.Green) blue = TextPropertySet(colour=styles.Colours.Blue) yellow = TextPropertySet(colour=styles.Colours.Yellow) p = Paragraph() p.append('This next word should be in ') p.append(Text('red', red)) p.append(', while the following should be in their respective ') p.append('colours: ', Text('blue ', blue), Text('green ', green)) p.append('and ', TEXT('yellow', colour=styles.Colours.Yellow), '.') # When specifying colours it is important to use the colours from the # style sheet supplied with the document and not the StandardColours # object each document get its own copy of the stylesheet so that # changes can be made on a document by document basis without mucking # up other documents that might be based on the same basic stylesheet. section.append(p) return doc