Beispiel #1
0
def customize_rtf_file(rtf_document):
    section = rtf_document.Sections[0]
    ss = rtf_document.StyleSheet
    p1 = Paragraph(ss.ParagraphStyles.Normal)
    footer = '''COPYRIGHT & DISCLAIMER: This report and its contents are for the use of AAPNewswire subscribers only and may not be provided to any third party for any purpose whatsoever without the express written permission of Australian Associated Press Pty Ltd. The material contained in this report is for general information purposes only. Any figures in this report are an estimation and should not be taken as definitive statistics. Subscribers should refer to the original article before making any financial decisions or forming any opinions. AAP Newswire Monitoring makes no representations and, to the extent permitted by law, excludes all warranties in relation to the information contained in the report and is not liable to you or to any third party for any losses, costs or expenses, resulting from any use or misuse of the report.'''
    p1.append(LINE, footer, LINE, 'AAPNewswire report supplied by', LINE, 'Copyright AAPNewswire {}'.format(utcnow().strftime("%Y")))
    section.append(p1)
    return
Beispiel #2
0
    def get_monitoring_file(self, date_items_dict, monitoring_profile=None):
        _file = tempfile.NamedTemporaryFile()
        if not date_items_dict:
            return _file

        current_date = utc_to_local(app.config['DEFAULT_TIMEZONE'], utcnow()).strftime('%d/%m/%Y')
        doc = Document()
        section = Section()
        ss = doc.StyleSheet
        p1 = Paragraph(ss.ParagraphStyles.Heading1)
        p1.append('{} Monitoring: {} ({})'.format(app.config.get('MONITORING_REPORT_NAME', 'Newsroom'),
                                                  monitoring_profile['name'], current_date))
        section.append(p1)

        for d in date_items_dict.keys():
            date_p = Paragraph(ss.ParagraphStyles.Normal)
            date_p.append(LINE, d.strftime('%d/%m/%Y'))
            section.append(date_p)
            for item in date_items_dict[d]:
                self.format_item(item, ss, monitoring_profile, section)

        doc.Sections.append(section)
        app.customize_rtf_file(doc)

        doc.write(_file.name)
        return _file
Beispiel #3
0
    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
Beispiel #4
0
    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
Beispiel #5
0
    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)
Beispiel #6
0
def write_rtf(fh, fout):
    """
    Writes the text found in fh to rtf found in fout
    """
    wordpad_header = textwrap.dedent(r'''
        {\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset255 Times New Roman;}
        {\*\generator Riched20 10.0.14393}\viewkind4\uc1
        ''').strip().replace('\n', '\r\n')
    center_space = '            '

    r = Renderer()

    doc = Document()
    ss = doc.StyleSheet
    sec = Section()
    doc.Sections.append(sec)

    is_blank = False
    paragraph_text = ['']
    for line in fh:
        if not line or line.isspace():
            is_blank = True
        if is_blank:
            # first element of paragraph_text is left-aligned, subsequent
            # elements are centered
            is_centered = False
            for sec_line in paragraph_text:
                if is_centered:
                    para_props = ParagraphPropertySet(
                        alignment=ParagraphPropertySet.CENTER)
                    p = Paragraph(ss.ParagraphStyles.Normal, para_props)
                    p.append(sec_line)
                    sec.append(p)
                elif sec_line:  # first element may be nothing, but not whitespace
                    sec.append(sec_line)
                is_centered = True
            is_blank = False
            paragraph_text = ['']
        if line.startswith(center_space):
            paragraph_text.append(line.strip())
            is_blank = True
        else:
            paragraph_text[0] += ' ' + line
            paragraph_text[0] = paragraph_text[0].strip()

    fout.write(wordpad_header)
    r.Write(doc, fout)
Beispiel #7
0
 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)
Beispiel #8
0
 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
Beispiel #9
0
 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
Beispiel #10
0
    def get_monitoring_file(self, date_items_dict, monitoring_profile=None):
        _file = tempfile.NamedTemporaryFile()
        if not date_items_dict:
            return _file

        current_date = utc_to_local(app.config['DEFAULT_TIMEZONE'],
                                    utcnow()).strftime('%d/%m/%Y')
        doc = Document()
        section = Section()
        ss = doc.StyleSheet

        general_settings = get_settings_collection().find_one(
            GENERAL_SETTINGS_LOOKUP)
        if general_settings and general_settings['values'].get(
                'monitoring_report_logo_path'):
            image_filename = general_settings['values'].get(
                'monitoring_report_logo_path')
            if os.path.exists(image_filename):
                try:
                    image = LogoImage(general_settings['values'].get(
                        'monitoring_report_logo_path'))
                    section.append(Paragraph(image))
                except Exception as e:
                    logger.exception(e)
                    logger.error(
                        'Failed to open logo image {}'.format(image_filename))
            else:
                logger.error(
                    'Unable to find logo image {}'.format(image_filename))

        p1 = Paragraph(ss.ParagraphStyles.Heading1)
        p1.append('{} Monitoring: {} ({})'.format(
            app.config.get('MONITORING_REPORT_NAME', 'Newsroom'),
            monitoring_profile['name'], current_date))
        section.append(p1)

        for d in date_items_dict.keys():
            date_p = Paragraph(ss.ParagraphStyles.Normal)
            date_p.append(LINE, d.strftime('%d/%m/%Y'))
            section.append(date_p)
            for item in date_items_dict[d]:
                self.format_item(item, ss, monitoring_profile, section)

        doc.Sections.append(section)
        app.customize_rtf_file(doc)

        doc.write(_file.name)
        return _file
Beispiel #11
0
    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
Beispiel #12
0
    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
Beispiel #13
0
    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
Beispiel #14
0
 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
Beispiel #15
0
    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
Beispiel #16
0
    def format_item(self, item, styles, monitoring_profile, section):
        keywords = get_keywords_in_text(item.get('body_str'),
                                        (monitoring_profile
                                         or {}).get('keywords', []))

        p2 = Paragraph(styles.ParagraphStyles.Normal)
        p2.append(LINE,
                  TEXT('Headline: {}'.format(item.get('headline')), bold=True))
        p2.append(LINE, TEXT('Source: {}'.format(item.get('source')),
                             bold=True))
        p2.append(LINE,
                  TEXT('Keywords: {}'.format(', '.join(keywords)), bold=True))
        if item.get('byline'):
            p2.append(LINE, ('By ' + item['byline']))

        p3 = Paragraph(styles.ParagraphStyles.Normal)
        body_lines = item.get('body_str', '').split('\n')
        for line in body_lines:
            p3.append(line, LINE, LINE)

        if monitoring_profile['alert_type'] == 'linked_text':
            p3.append(
                LINE, LINE,
                RawCode(r'{\field {\*\fldinst HYPERLINK "' +
                        url_for_wire(item, True, section='monitoring') +
                        r'"}{\fldrslt{\ul View Article}}}'))
        section.append(p2)
        section.append(p3)
Beispiel #17
0
    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
Beispiel #18
0
    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
Beispiel #19
0
 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
Beispiel #20
0
 def make_paraHeading():
     doc, section, styles = RTFTestCase.initializeDoc()
     p1 = Paragraph(styles.ParagraphStyles.Heading1)
     p1.append('Heading 1')
     section.append(p1)
     return doc
Beispiel #21
0
    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')
Beispiel #22
0
    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 balance_table(rows, number_of_observations_1, number_of_observations_2):
    #from PyRTF.Elements import Document, Section, BorderPropertySet, FramePropertySet, Table
    from PyRTF.utils import RTFTestCase
    from PyRTF.Elements import Document
    from PyRTF.document.section import Section
    from PyRTF.document.paragraph import Cell, Paragraph, Table
    #from PyRTF.Styles import TextStyle, ParagraphStyle
    from PyRTF.document.character import Text
    from PyRTF.PropertySets import BorderPropertySet, FramePropertySet, MarginsPropertySet, ParagraphPropertySet, TabPropertySet, TextPropertySet
    #
    doc = Document()
    ss = doc.StyleSheet
    section = Section()
    doc.Sections.append(section)
    #
    thin_edge = BorderPropertySet(width=20,
                                  style=BorderPropertySet.SINGLE,
                                  colour=ss.Colours.Black)
    thick_edge = BorderPropertySet(width=80, style=BorderPropertySet.SINGLE)
    zero_edge_thin = BorderPropertySet(width=20,
                                       style=BorderPropertySet.SINGLE,
                                       colour=ss.Colours.White)
    #
    thin_frame = FramePropertySet(thin_edge, thin_edge, thin_edge, thin_edge)
    thick_frame = FramePropertySet(thick_edge, thick_edge, thick_edge,
                                   thick_edge)
    thin_frame_top_only = FramePropertySet(top=thin_edge,
                                           left=None,
                                           bottom=None,
                                           right=None)
    thin_frame_bottom_only = FramePropertySet(top=None,
                                              left=None,
                                              bottom=thin_edge,
                                              right=None)
    thin_frame_top_and_bottom_only = FramePropertySet(top=thin_edge,
                                                      left=None,
                                                      bottom=thin_edge,
                                                      right=None)
    zero_frame = FramePropertySet(top=None, left=None, bottom=None, right=None)
    #
    table = Table(TabPropertySet.DEFAULT_WIDTH * 5,
                  TabPropertySet.DEFAULT_WIDTH * 3,
                  TabPropertySet.DEFAULT_WIDTH * 3)
    #
    c1 = Cell(Paragraph(''), thin_frame_top_and_bottom_only)
    c2 = Cell(Paragraph("Republican ('Control')"),
              thin_frame_top_and_bottom_only)
    c3 = Cell(Paragraph("Democrat ('Treatment')"),
              thin_frame_top_and_bottom_only)
    table.AddRow(c1, c2, c3)
    #rows_statistical_significance_1
    c1 = Cell(Paragraph(rows[0][0]), zero_frame)
    c2 = Cell(Paragraph(rows[0][1]), zero_frame)
    c3 = Cell(Paragraph(rows[0][2]), zero_frame)
    table.AddRow(c1, c2, c3)
    #
    c1 = Cell(Paragraph(rows[1][0]), zero_frame)
    c2 = Cell(Paragraph(rows[1][1]), zero_frame)
    c3 = Cell(Paragraph(rows[1][2]), zero_frame)
    table.AddRow(c1, c2, c3)
    #
    c1 = Cell(Paragraph(rows[2][0]), zero_frame)
    c2 = Cell(Paragraph(rows[2][1]), zero_frame)
    c3 = Cell(Paragraph(rows[2][2]), zero_frame)
    table.AddRow(c1, c2, c3)
    #
    #c1 = Cell(Paragraph(''), thin_frame_bottom_only)
    #c2 = Cell(Paragraph('(.013)'), thin_frame_bottom_only)
    #c3 = Cell(Paragraph('tbd'), thin_frame_bottom_only)
    #table.AddRow(c1, c2)
    #
    c1 = Cell(Paragraph('Observations'), thin_frame_top_and_bottom_only)
    c2 = Cell(Paragraph(number_of_observations_1),
              thin_frame_top_and_bottom_only)
    c3 = Cell(Paragraph(number_of_observations_2),
              thin_frame_top_and_bottom_only)
    table.AddRow(c1, c2, c3)
    #
    section.append(table)
    #
    return doc
Beispiel #24
0
 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 basic_table():
    #from PyRTF.Elements import Document, Section, BorderPropertySet, FramePropertySet, Table
    from PyRTF.utils import RTFTestCase
    from PyRTF.Elements import Document
    from PyRTF.document.section import Section
    from PyRTF.document.paragraph import Cell, Paragraph, Table
    #from PyRTF.Styles import TextStyle, ParagraphStyle
    from PyRTF.document.character import Text
    from PyRTF.PropertySets import BorderPropertySet, FramePropertySet, MarginsPropertySet, ParagraphPropertySet, TabPropertySet, TextPropertySet
    #
    doc = Document()
    ss = doc.StyleSheet
    section = Section()
    doc.Sections.append(section)
    #
    thin_edge = BorderPropertySet(width=20,
                                  style=BorderPropertySet.SINGLE,
                                  colour=ss.Colours.Black)
    thick_edge = BorderPropertySet(width=80, style=BorderPropertySet.SINGLE)
    zero_edge_thin = BorderPropertySet(width=20,
                                       style=BorderPropertySet.SINGLE,
                                       colour=ss.Colours.White)
    #
    thin_frame = FramePropertySet(thin_edge, thin_edge, thin_edge, thin_edge)
    thick_frame = FramePropertySet(thick_edge, thick_edge, thick_edge,
                                   thick_edge)
    thin_frame_top_only = FramePropertySet(top=thin_edge,
                                           left=None,
                                           bottom=None,
                                           right=None)
    thin_frame_bottom_only = FramePropertySet(top=None,
                                              left=None,
                                              bottom=thin_edge,
                                              right=None)
    thin_frame_top_and_bottom_only = FramePropertySet(top=thin_edge,
                                                      left=None,
                                                      bottom=thin_edge,
                                                      right=None)
    #
    table = Table(TabPropertySet.DEFAULT_WIDTH * 5,
                  TabPropertySet.DEFAULT_WIDTH * 3)
    #
    c1 = Cell(Paragraph(''), thin_frame_top_and_bottom_only)
    c2 = Cell(Paragraph('Recommends AI'), thin_frame_top_and_bottom_only)
    #c3 = Cell(Paragraph('tbd'), thin_frame_top_and_bottom_only)
    table.AddRow(c1, c2)
    #
    c1 = Cell(Paragraph('Read ethics article'), thin_frame_top_only)
    c2 = Cell(Paragraph('-.38***'), thin_frame_top_only)
    #c3 = Cell(Paragraph('tbd'), thin_frame_top_only)
    table.AddRow(c1, c2)
    #
    c1 = Cell(Paragraph(''), thin_frame_bottom_only)
    c2 = Cell(Paragraph('(.013)'), thin_frame_bottom_only)
    #c3 = Cell(Paragraph('tbd'), thin_frame_bottom_only)
    table.AddRow(c1, c2)
    #
    c1 = Cell(Paragraph('Observations'), thin_frame_top_only)
    c2 = Cell(Paragraph('5000'), thin_frame_top_only)
    #c3 = Cell(Paragraph('tbd'), thin_frame_top_and_bottom_only)
    table.AddRow(c1, c2)
    #
    tps = TextPropertySet(italic=True)
    text = Text('R^2', tps)
    #
    #c1 = Cell(Paragraph('R^2', text), thin_frame_bottom_only)
    c1 = Cell(Paragraph(text), thin_frame_bottom_only)
    c2 = Cell(Paragraph('0.147'), thin_frame_bottom_only)
    #c3 = Cell(Paragraph('tbd'), thin_frame_bottom_only)
    table.AddRow(c1, c2)
    #
    section.append(table)
    #
    section.append('Standard errors in parentheses')
    section.append('* p<0.1, ** p<0.05, *** p<0.01')
    #
    return doc
Beispiel #26
0
    def getParagraph(self, **kwargs):
        from PyRTF.document.paragraph import Paragraph

        prefix_element = kwargs.pop('prefix', None)

        self._convert_text(**kwargs)

        element_obj = Paragraph()
        if self._style is not None:
            element_obj.Style = self._style
        if prefix_element:
            element_obj.append(prefix_element)
            element_obj.append(unicode(self.DELIMITER_PREFIX))
        if isinstance(self._text_elements, (list, tuple)):
            for atext in self._text_elements:
                element_obj.append(atext)
        else:
            element_obj.append(self._text_elements)
        return element_obj
def basic_table_with_input(dependent_variable_name,
                           rows_statistical_significance,
                           number_of_observations, r_squared):
    #from PyRTF.Elements import Document, Section, BorderPropertySet, FramePropertySet, Table
    from PyRTF.utils import RTFTestCase
    from PyRTF.Elements import Document
    from PyRTF.document.section import Section
    from PyRTF.document.paragraph import Cell, Paragraph, Table
    #from PyRTF.Styles import TextStyle, ParagraphStyle
    from PyRTF.document.character import Text
    from PyRTF.PropertySets import BorderPropertySet, FramePropertySet, MarginsPropertySet, ParagraphPropertySet, TabPropertySet, TextPropertySet
    #
    doc = Document()
    ss = doc.StyleSheet
    section = Section()
    doc.Sections.append(section)
    #
    thin_edge = BorderPropertySet(width=20,
                                  style=BorderPropertySet.SINGLE,
                                  colour=ss.Colours.Black)
    thick_edge = BorderPropertySet(width=80, style=BorderPropertySet.SINGLE)
    zero_edge_thin = BorderPropertySet(width=20,
                                       style=BorderPropertySet.SINGLE,
                                       colour=ss.Colours.White)
    #
    thin_frame = FramePropertySet(thin_edge, thin_edge, thin_edge, thin_edge)
    thick_frame = FramePropertySet(thick_edge, thick_edge, thick_edge,
                                   thick_edge)
    thin_frame_top_only = FramePropertySet(top=thin_edge,
                                           left=None,
                                           bottom=None,
                                           right=None)
    thin_frame_bottom_only = FramePropertySet(top=None,
                                              left=None,
                                              bottom=thin_edge,
                                              right=None)
    thin_frame_top_and_bottom_only = FramePropertySet(top=thin_edge,
                                                      left=None,
                                                      bottom=thin_edge,
                                                      right=None)
    zero_frame = FramePropertySet(top=None, left=None, bottom=None, right=None)
    #
    table = Table(TabPropertySet.DEFAULT_WIDTH * 5,
                  TabPropertySet.DEFAULT_WIDTH * 3,
                  TabPropertySet.DEFAULT_WIDTH * 3)
    #
    c1 = Cell(Paragraph(''), thin_frame_top_and_bottom_only)
    c2 = Cell(Paragraph(dependent_variable_name + ' - coeff'),
              thin_frame_top_and_bottom_only)
    c3 = Cell(Paragraph(dependent_variable_name + ' - Std error'),
              thin_frame_top_and_bottom_only)
    table.AddRow(c1, c2, c3)
    #
    for row in rows_statistical_significance:
        c1 = Cell(Paragraph(row[0]), zero_frame)
        c2 = Cell(Paragraph(row[1]), zero_frame)
        c3 = Cell(Paragraph(row[2]), zero_frame)
        table.AddRow(c1, c2, c3)
    #
    #c1 = Cell(Paragraph(''), thin_frame_bottom_only)
    #c2 = Cell(Paragraph('(.013)'), thin_frame_bottom_only)
    #c3 = Cell(Paragraph('tbd'), thin_frame_bottom_only)
    #table.AddRow(c1, c2)
    #
    c1 = Cell(Paragraph('Observations'), thin_frame_top_only)
    c2 = Cell(Paragraph(number_of_observations), thin_frame_top_only)
    c3 = Cell(Paragraph(''), thin_frame_top_only)
    table.AddRow(c1, c2, c3)
    #
    tps = TextPropertySet(italic=True)
    text = Text('R^2', tps)
    #
    #c1 = Cell(Paragraph('R^2', text), thin_frame_bottom_only)
    c1 = Cell(Paragraph(text), thin_frame_bottom_only)
    c2 = Cell(Paragraph(r_squared), thin_frame_bottom_only)
    c3 = Cell(Paragraph(''), thin_frame_bottom_only)
    table.AddRow(c1, c2, c3)
    #
    section.append(table)
    #
    section.append('Standard errors in parentheses')
    section.append('* p<0.1, ** p<0.05, *** p<0.01')
    #
    return doc
Beispiel #28
0
    def getTable(self, **kwargs):
        """
        @param table_left_offset (integer)
        @param merged_footer whether combine the content of all the footer cells into one paragraph (boolean)
        @param space_before_footer insert blank line before the merged footer paragraph (boolean)
        """
        from PyRTF.document.paragraph import Paragraph, Table, Cell
        #from PyRTF.PropertySets import ParagraphPropertySet

        self._convert_table(**kwargs)
        col_count = self._table_elements['col.cnt']

        tbl_left_offset = kwargs.get('table_left_offset', 108)
        ret = Table(left_offset=tbl_left_offset)
        tbl_layout = self._get_column_layout(col_count, **kwargs)
        ret.SetColumnWidths(*(tbl_layout))

        if len(self._table_elements['head']) > 0:
            header_row = list()
            for a_head in self._table_elements['head'][:col_count]:
                head_p = Paragraph(a_head['value'])
                if self._head_style:
                    head_p.Style = self._head_style
                rhead = Cell(head_p)
                header_row.append(rhead)
            ret.AddRow(*header_row)

        for row in self._table_elements['body']:
            single_row = list()
            for a_cell in row[:col_count]:
                cell_p = Paragraph(a_cell['value'])
                if self._cell_style:
                    cell_p.Style = self._cell_style
                rcell = Cell(cell_p)
                single_row.append(rcell)
            ret.AddRow(*single_row)

        if len(self._table_elements['foot']) > 0:
            if kwargs.get('merged_footer', True):
                combined = list()
                combined.append(ret)
                if kwargs.get('space_before_footer', True):
                    spacer_p = Paragraph('')
                    combined.append(spacer_p)
                foot_p = Paragraph(self._table_elements['foot'][0]['value'])
                if self._foot_style:
                    foot_p.Style = self._foot_style
                combined.append(foot_p)
                # override rvalue;
                ret = tuple(combined)
            else:
                foot_row = list()
                for a_foot in self._table_elements['foot'][:col_count]:
                    foot_p = Paragraph(a_foot['value'])
                    if self._foot_style:
                        foot_p.Style = self._foot_style
                    rfoot = Cell(foot_p)
                    foot_row.append(rfoot)
                ret.AddRow(*foot_row)
        return ret