예제 #1
0
def count_size(wh_list, row):
    """Count height of image row.

    Args:
        wh_list - list with attributes, contains width and height:
        row - image row.

    """
    height, width = -1, -1
    for l in wh_list:
        if l[0] == 'width':
            width = float(l[1].replace('in', ''))
        if l[0] == 'height':
            height = float(l[1].replace('in', ''))
    if height == -1 or width == -1:
        width = ININTENCM
        height = ININTENCM
    if width > ININTENCM:
        new_width = ININTENCM
        new_height = height * new_width / width
    else:
        new_width = width
        new_height = height
    height_set = str(new_height) + 'in'
    new_name = 'image' + str(image_counter)
    height_suit = Style(name=new_name, family='table-row')
    height_suit.addElement(TableRowProperties(rowheight=height_set))

    ods.automaticstyles.addElement(height_suit)
    row.setAttribute(attr='stylename', value=new_name)

    new_width = str(new_width) + 'in'
    new_height = height_set
    return new_width, new_height
예제 #2
0
 def colwidth(w):
     if not hasattr(colwidth,'num'): colwidth.num=0
     colwidth.num+=1
     width=Style(name="W{}".format(colwidth.num),family="table-column")
     width.addElement(TableColumnProperties(columnwidth=w))
     doc.automaticstyles.addElement(width)
     return width
    def add_style(self, name, family, styles, **kwargs):
        style = Style(name=name, family=family, **kwargs)

        for v in styles:
            style.addElement(v)

        self._document.automaticstyles.addElement(style)
예제 #4
0
    def test_percentage(self):
        """ Test that an automatic style can refer to a PercentageStyle as a datastylename """
        doc = OpenDocumentSpreadsheet()
        nonze = PercentageStyle(name='N11')
        nonze.addElement(Number(decimalplaces='2', minintegerdigits='1'))
        nonze.addElement(Text(text='%'))
        doc.automaticstyles.addElement(nonze)
        pourcent = Style(name='pourcent', family='table-cell', datastylename='N11')
        pourcent.addElement(ParagraphProperties(textalign='center'))
        pourcent.addElement(TextProperties(attributes={'fontsize':"10pt",'fontweight':"bold", 'color':"#000000" }))
        doc.automaticstyles.addElement(pourcent)

        table = Table(name='sheet1')
        tr = TableRow()
        tc = TableCell(formula='=AVERAGE(C4:CB62)/2',stylename='pourcent', valuetype='percentage')
        tr.addElement(tc)
        table.addElement(tr)
        doc.spreadsheet.addElement(table)
        doc.save("TEST.odt")
        self.saved = True
        d = load("TEST.odt")
        result = d.contentxml()
        self.assertNotEqual(-1, result.find(u'''<number:percentage-style'''))
        self.assertNotEqual(-1, result.find(u'''style:data-style-name="N11"'''))
        self.assertNotEqual(-1, result.find(u'''style:name="pourcent"'''))
예제 #5
0
 def colwidth(self, width):
     if width not in self._widthstyles:
         w = Style(name="W{}".format(width), family="table-column")
         w.addElement(TableColumnProperties(columnwidth=width))
         self.doc.automaticstyles.addElement(w)
         self._widthstyles[width] = w
     return self._widthstyles[width]
예제 #6
0
 def addText(self, data_box):
     text = data_box.getText()
     frame_style = Style(name='FrameStyle', family='graphic')
     debug('Angle: %s', data_box.text_data.angle)
     angle = data_box.text_data.angle
     if angle:
         frame_style = Style(name='FrameStyleRotated', family='graphic')
     x, y, width, height = data_box.getBoundsPrintSize(
         self.current_page_resolution)
     frame = Frame(stylename=frame_style,
                   width=str(width) + 'in',
                   height=str(height) + 'in',
                   x=str(x) + 'in',
                   y=str(y) + 'in',
                   anchortype='paragraph')
     if angle:
         frame.addAttribute(
             'transform', 'rotate (%s) translate (%scm %scm)' %
             (abs(math.radians(angle)), x, y))
     self.current_page.addElement(frame)
     textbox = TextBox()
     frame.addElement(textbox)
     for line in text.split('\n'):
         textbox.addElement(
             P(stylename=self.__handleFrameStyle(data_box.text_data),
               text=line))
예제 #7
0
파일: files.py 프로젝트: C-Element/SigeLib
def generate_ods(data):
    """
    Generate a ODS file.
    :param data: list-like of dict with the data.
    :return:
    """
    doc = OpenDocumentSpreadsheet()
    table = Table()
    tr = TableRow()
    colautowidth = Style(name="co1", family="table-column")
    colautowidth.addElement(TableColumnProperties(useoptimalcolumnwidth=True))
    doc.automaticstyles.addElement(colautowidth)
    for column in data[0].keys():
        table.addElement(TableColumn(stylename=colautowidth))
        tc = TableCell(valuetype="string", value=column)
        tc.addElement(P(text=column))
        tr.addElement(tc)
    table.addElement(tr)
    for row in data:
        tr = TableRow()
        for column in row.keys():
            tc = TableCell(valuetype="string", value=row[column])
            tc.addElement(P(text=row[column]))
            tr.addElement(tc)
        table.addElement(tr)
    file = os.path.join(
        tempfile.gettempdir(),
        'SIGE' + datetime.now().strftime('%Y%m%d%H%M%S%f') + '.ods')
    doc.spreadsheet.addElement(table)
    print(doc.automaticstyles.childNodes[0].attributes)
    doc.save(file)
    return file
예제 #8
0
 def colwidth(self, width):
     if width not in self._widthstyles:
         w = Style(name="W{}".format(width), family="table-column")
         w.addElement(TableColumnProperties(columnwidth=width))
         self.doc.automaticstyles.addElement(w)
         self._widthstyles[width] = w
     return self._widthstyles[width]
예제 #9
0
def extract_highlight_odf(name):
    textdoc = OpenDocumentText()
    location = os.path.join("/tmp/pdf_highlight/", name)
    doc_mask = fitzopen(location)
    doc_text = fitzopen(location)
    nb_pages = doc_text.pageCount
    style_p = Style(name="P1", family="paragraph", parentstylename="Standard")
    p_prop = ParagraphProperties(textalign="justify",
                                 justifysingleword="false")
    style_p.addElement(p_prop)
    textdoc.automaticstyles.addElement(style_p)
    textdoc.text.addElement(P(stylename=style_p, text=f"{name}\n\n"))

    for i in range(nb_pages):
        rect, hierarchy = Page_Get_Rects(doc_mask, doc_text, name, i)
        if rect.shape[0] > 0:
            textdoc = Page_Rect_get_Text_odf(doc_text, name, i, rect,
                                             hierarchy, textdoc, style_p)

    text_name = name.replace(".pdf", ".odt")
    location_out = os.path.join("/tmp/pdf_highlight/", text_name)

    textdoc.save(location_out)
    #print('fin')
    return text_name, location_out
예제 #10
0
    def create_doc(self):
        doc = OpenDocumentText()

        # Page layout: A4
        pagelayout = PageLayout(name="A4")
        doc.automaticstyles.addElement(pagelayout)
        pagelayout.addElement(
            PageLayoutProperties(margin="2cm",
                                 pageheight="297mm",
                                 pagewidth="210mm",
                                 printorientation="portrait"))
        # Use page layout on master page, to set it:
        masterpage = MasterPage(name="Standard", pagelayoutname="A4")
        doc.masterstyles.addElement(masterpage)

        # Styles
        s = doc.styles
        self.h1style = Style(name="Heading 1", family="paragraph")
        self.h1style.addElement(
            TextProperties(attributes={
                'fontsize': "24pt",
                'fontweight': "bold"
            }))
        s.addElement(self.h1style)
        return doc
예제 #11
0
파일: files.py 프로젝트: C-Element/SigeLib
def generate_ods(data):
    """
    Generate a ODS file.
    :param data: list-like of dict with the data.
    :return:
    """
    doc = OpenDocumentSpreadsheet()
    table = Table()
    tr = TableRow()
    colautowidth = Style(name="co1", family="table-column")
    colautowidth.addElement(TableColumnProperties(useoptimalcolumnwidth=True))
    doc.automaticstyles.addElement(colautowidth)
    for column in data[0].keys():
        table.addElement(TableColumn(stylename=colautowidth))
        tc = TableCell(valuetype="string", value=column)
        tc.addElement(P(text=column))
        tr.addElement(tc)
    table.addElement(tr)
    for row in data:
        tr = TableRow()
        for column in row.keys():
            tc = TableCell(valuetype="string", value=row[column])
            tc.addElement(P(text=row[column]))
            tr.addElement(tc)
        table.addElement(tr)
    file = os.path.join(tempfile.gettempdir(), 'SIGE' +
                        datetime.now().strftime('%Y%m%d%H%M%S%f') + '.ods')
    doc.spreadsheet.addElement(table)
    print(doc.automaticstyles.childNodes[0].attributes)
    doc.save(file)
    return file
예제 #12
0
def sample():
    textdoc = OpenDocumentText()
    # Styles
    s = textdoc.styles
    h1style = Style(name="Heading 1", family="paragraph")
    h1style.addElement(
        TextProperties(attributes={
            'fontsize': "24pt",
            'fontweight': "bold"
        }))
    s.addElement(h1style)
    # An automatic style
    boldstyle = Style(name="Bold", family="text")
    boldprop = TextProperties(fontweight="bold")
    boldstyle.addElement(boldprop)
    textdoc.automaticstyles.addElement(boldstyle)
    # Text
    h = H(outlinelevel=1, stylename=h1style, text="My first texta")
    textdoc.text.addElement(h)
    p = P(text="Hello world. ")
    boldpart = Span(stylename=boldstyle, text="This part is bold. ")
    p.addElement(boldpart)
    p.addText("This is after bold.")

    quotStyle = Style(name="Quotations")
    marginaliaStyle = Style(name="Marginalia")

    # p2 = P(text="2nd par. ", stylename=textBodyStyle)
    p3 = P(text="3rd par. ", stylename=quotStyle)

    textdoc.text.addElement(p)
    textdoc.text.addElement(p2)
    textdoc.text.addElement(p3)
    a = textdoc.save("myfirstdocument.odt")
예제 #13
0
 def __handleFrameStyleRotated(self, text_data):
     style_name = "box%s%s%s%s%sRotated" % (
         text_data.face,
         text_data.size,
         text_data.line_space,
         text_data.letter_space,
         text_data.justification,
     )
     if not style_name in self.font_styles:
         frame_style = Style(name=style_name, family="paragraph")
         frame_style.addElement(
             ParagraphProperties(
                 linespacing="%spt" % text_data.line_space, textalign=self.convertTextAlign(text_data.justification)
             )
         )
         frame_style.addElement(
             TextProperties(
                 letterspacing="%spt" % text_data.letter_space,
                 fontstyle=self.convertFontStyle(text_data.style),
                 fontweight=self.convertFontWeight(text_data.weight),
                 fontsize="%spt" % text_data.size,
                 fontfamily=str(text_data.face),
             )
         )
         self.document.automaticstyles.addElement(frame_style)
         self.font_styles.append(style_name)
     return style_name
예제 #14
0
 def _add_headerstyle(self):
     header = Style(name="ColumnHeader", family="table-cell")
     header.addElement(
         ParagraphProperties(textalign="center"))
     header.addElement(
         TextProperties(fontweight="bold"))
     self.doc.styles.addElement(header)
     return header
예제 #15
0
def saltolinea(documento):
    withbreak = Style(name="WithBreak",
                      parentstylename="Standard",
                      family="paragraph")
    withbreak.addElement(ParagraphProperties(breakafter="page"))
    documento.automaticstyles.addElement(withbreak)
    p = P(stylename=withbreak)
    documento.text.addElement(p)
    return documento
예제 #16
0
 def addParagraphStyle(self, id, name, paragraph_properties={}, text_properties={}):
     """  """
     style = Style(name=name, family="paragraph")
     if len(paragraph_properties) > 0:
         style.addElement(ParagraphProperties(**paragraph_properties))
     if len(text_properties) > 0:
         style.addElement(TextProperties(**text_properties))
     setattr(self, id, style)
     self.document.styles.addElement(style)
예제 #17
0
 def newPage(self, page_data):
     master_name = self.__handlePageMaster(page_data)
     page_style_name = "%sPage" % master_name
     if not page_style_name in self.page_styles:
         page_style = Style(name=page_style_name, family="paragraph", masterpagename=master_name)
         page_style.addElement(ParagraphProperties(breakbefore="page"))
         self.document.automaticstyles.addElement(page_style)
     new_page = P(stylename=page_style_name)
     self.document.text.addElement(new_page)
     return new_page
예제 #18
0
 def _generate_styles(self):
     self._h1_style = Style(name="Heading 1", family="paragraph")
     self._h1_style.addElement(ParagraphProperties(attributes={"margintop": "24pt", "marginbottom": "12pt",
                                                               "keepwithnext": "always"}))
     self._h1_style.addElement(TextProperties(attributes={"fontsize": "16pt"}))
     self._document.styles.addElement(self._h1_style)
     self._p_style = Style(name="Body", family="paragraph")
     self._p_style.addElement(ParagraphProperties(attributes={"textindent": "1.25cm", "textalign": "justify",
                                                              "orphans": 2, "widows": 2}))
     self._document.styles.addElement(self._p_style)
예제 #19
0
class ExcercisesDoc:
    def __init__(self, count, min, max, filename):
        self.count = count
        self.min = min
        self.max = max
        self.filename = filename

    def create_doc(self):
        doc = OpenDocumentText()

        # Page layout: A4
        pagelayout = PageLayout(name="A4")
        doc.automaticstyles.addElement(pagelayout)
        pagelayout.addElement(
            PageLayoutProperties(margin="2cm",
                                 pageheight="297mm",
                                 pagewidth="210mm",
                                 printorientation="portrait"))
        # Use page layout on master page, to set it:
        masterpage = MasterPage(name="Standard", pagelayoutname="A4")
        doc.masterstyles.addElement(masterpage)

        # Styles
        s = doc.styles
        self.h1style = Style(name="Heading 1", family="paragraph")
        self.h1style.addElement(
            TextProperties(attributes={
                'fontsize': "24pt",
                'fontweight': "bold"
            }))
        s.addElement(self.h1style)
        return doc

    def render(self):
        doc = self.create_doc()
        for block_id in range(0, self.count, 10):
            block_num = block_id / 10 + 1
            self.render_block(doc, block_num)
        doc.save(self.filename)

    def render_block(self, doc, num):
        problems = generate_problems(10, self.min, self.max)
        self.render_subblock(doc, num, problems, 'Aufgaben', False)
        self.render_subblock(doc, num, problems, 'Lösungen', True)

    def render_subblock(self, doc, num, problems, text, show_solution):
        base = (num - 1) * 10 + 1
        doc.text.addElement(
            H(outlinelevel=1,
              stylename=self.h1style,
              text="{} Teil {}".format(text, num)))
        for i, p in enumerate(problems):
            p = P(text="{}) {}".format(base + i, p.render(show_solution)))
            doc.text.addElement(p)
        doc.text.addElement(P())
예제 #20
0
파일: odt.py 프로젝트: ocarneiro/pylotex
 def setup(self):
     odt = self.generator
     s = odt.styles
     h1s = Style(name="Heading 1", family="paragraph")
     h1s.addElement(
          TextProperties(
              attributes={'fontsize': "24pt",
                          'fontweight': "bold"}
                        )
                   )
     s.addElement(h1s)
     self.h1s = h1s
예제 #21
0
 def newPage(self, page_data):
     master_name = self.__handlePageMaster(page_data)
     page_style_name = '%sPage' % master_name
     if not page_style_name in self.page_styles:
         page_style = Style(name=page_style_name,
                            family='paragraph',
                            masterpagename=master_name)
         page_style.addElement(ParagraphProperties(breakbefore='page'))
         self.document.automaticstyles.addElement(page_style)
     new_page = P(stylename=page_style_name)
     self.document.text.addElement(new_page)
     return new_page
예제 #22
0
    def _process_style(self, style: dict[str, Any]) -> str:
        """Convert a style dictionary to a OpenDocument style sheet

        Parameters
        ----------
        style : Dict
            Style dictionary

        Returns
        -------
        style_key : str
            Unique style key for later reference in sheet
        """
        from odf.style import (
            ParagraphProperties,
            Style,
            TableCellProperties,
            TextProperties,
        )

        if style is None:
            return None
        style_key = json.dumps(style)
        if style_key in self._style_dict:
            return self._style_dict[style_key]
        name = f"pd{len(self._style_dict)+1}"
        self._style_dict[style_key] = name
        odf_style = Style(name=name, family="table-cell")
        if "font" in style:
            font = style["font"]
            if font.get("bold", False):
                odf_style.addElement(TextProperties(fontweight="bold"))
        if "borders" in style:
            borders = style["borders"]
            for side, thickness in borders.items():
                thickness_translation = {"thin": "0.75pt solid #000000"}
                odf_style.addElement(
                    TableCellProperties(
                        attributes={
                            f"border{side}": thickness_translation[thickness]
                        }))
        if "alignment" in style:
            alignment = style["alignment"]
            horizontal = alignment.get("horizontal")
            if horizontal:
                odf_style.addElement(ParagraphProperties(textalign=horizontal))
            vertical = alignment.get("vertical")
            if vertical:
                odf_style.addElement(
                    TableCellProperties(verticalalign=vertical))
        self.book.styles.addElement(odf_style)
        return name
예제 #23
0
    def __setDefaultStyle(self):
        DefaultStyle = Style(name="Standard", family='paragraph')
        DefaultStyle.addElement(TextProperties(
            fontfamily='FreeSans',
            fontsize='10pt'))
        DefaultStyle.addElement(ParagraphProperties(
            margintop='0.423cm',
            marginbottom='0.212cm'))
        self.__doc.styles.addElement(DefaultStyle)

        ''' Text Body '''
        txt = Style(name='text_20_body', family='paragraph', parentstylename='Standard')
        self.__doc.styles.addElement(txt)
def border_spices(an_odt, a_spice, a_font):
	## graphic
	border_stylename = a_spice + "border_style"
	border_graphic_style = Style(name=border_stylename, family="graphic")
	#href = an_odt.addPicture(a_spice + ".jpg")
	#if a_spice == "kristallen":
	#	border_graphic_properties = GraphicProperties(border="0.5mm double #000000")
	#elif a_spice == "roze":
	#	border_graphic_properties = GraphicProperties(border="0.5mm double #000000")
	#else:
	#	border_graphic_properties = GraphicProperties(border="0.5mm double #000000")
	border_graphic_properties = GraphicProperties(border="0.5mm double #000000")
	border_graphic_style.addElement(border_graphic_properties)
	border_beehive = beehive(an_odt, border_graphic_style,
							"273mm", "194mm", "-12mm", "-12mm", "1")
	border_frame = border_beehive["frame"]
	border_textbox = border_beehive["textbox"]

	## textgraph
	border_stylename = "emptygif"
	border_textgraph_style = Style(name=border_stylename, family="paragraph")
	border_text_props = TextProperties()
	border_textgraph_style.addElement(border_text_props)
	border_paragraph_props = ParagraphProperties()
	border_textgraph_style.addElement(border_paragraph_props)
	an_odt.styles.addElement(border_textgraph_style)

	text_unit(an_odt, border_textgraph_style, u"", border_textbox)

	an_odt.text.addElement(border_frame)
예제 #25
0
    def write(self):
        super().write()
        self.doc = OpenDocumentSpreadsheet()

        self.cell_formats = {}
        for key, value in self.colours.items():
            style = Style(name=key, family="table-cell")
            style.addElement(TableCellProperties(backgroundcolor="#" + value))
            self.doc.automaticstyles.addElement(style)
            self.cell_formats[key] = style

        for sheet in self.sheets:
            self.write_table(sheet)
        self.doc.save(self.filename, True)
def image_spices(an_odt, a_spice, a_font):
	## graphic
	image_stylename = a_spice + "frame_style"
	image_graphic_style = Style(name=image_stylename, family="graphic")
	href = an_odt.addPicture(a_spice + ".jpg")
	if a_spice == "chocolade":
		backgroundimage = BackgroundImage(href=href, position="top left", repeat="no")
	elif a_spice == "koraal":
		backgroundimage = BackgroundImage(href=href, position="bottom right", repeat="no")
	else:
		backgroundimage = BackgroundImage(href=href, position="top left", repeat="repeat")
	image_graphic_properties = GraphicProperties(border="0.5mm double #000000")
	image_graphic_properties.addElement(backgroundimage)
	image_graphic_style.addElement(image_graphic_properties)
	image_beehive = beehive(an_odt, image_graphic_style,
							"273mm", "194mm", "-12mm", "-12mm", "1")
	image_frame = image_beehive["frame"]
	image_textbox = image_beehive["textbox"]

	## textgraph
	image_stylename = "emptygif"
	image_textgraph_style = Style(name=image_stylename, family="paragraph")
	image_text_props = TextProperties()
	image_textgraph_style.addElement(image_text_props)
	image_paragraph_props = ParagraphProperties()
	image_textgraph_style.addElement(image_paragraph_props)
	an_odt.styles.addElement(image_textgraph_style)

	text_unit(an_odt, image_textgraph_style, u"", image_textbox)

	an_odt.text.addElement(image_frame)
예제 #27
0
def _create_style(name, family=None, **kwargs):
    """Helper function for creating a new style."""
    if family == 'paragraph' and 'marginbottom' not in kwargs:
        kwargs['marginbottom'] = '.5cm'
    style = Style(name=name, family=family)
    # Extract paragraph properties.
    kwargs_par = {}
    keys = sorted(kwargs.keys())
    for k in keys:
        if 'margin' in k:
            kwargs_par[k] = kwargs.pop(k)
    style.addElement(TextProperties(**kwargs))
    if kwargs_par:
        style.addElement(ParagraphProperties(**kwargs_par))
    return style
예제 #28
0
 def _add_datestyle(self, name="Date", include_time=False):
     """Construct a date style"""
     slash = number.Text()
     slash.addText('/')
     ds = number.DateStyle(name="Date",
                           automaticorder="true",
                           formatsource="language")
     ds.addElement(number.Day())
     ds.addElement(slash)
     ds.addElement(number.Month())
     ds.addElement(slash)
     ds.addElement(number.Year())
     if include_time:
         space = number.Text()
         space.addText(' ')
         colon = number.Text()
         colon.addText(':')
         ds.addElement(space)
         ds.addElement(number.Hours())
         ds.addElement(colon)
         ds.addElement(number.Minutes())
     self.doc.styles.addElement(ds)
     datestyle = Style(name=name,
                       family="table-cell",
                       parentstylename="Default",
                       datastylename=name)
     self.doc.styles.addElement(datestyle)
     return datestyle
예제 #29
0
	def add_title_page(self, odt, title):
		# Requirements for <project name>
		# <project description>
		#
		# Author: <stakeholder name>
		# <date>
		#
		# <document description>
		# Title
		titlestyle = Style(name="TitleStyle",family="text")
		titlestyle.addElement(TextProperties(attributes={'fontweight':"bold", 'fontsize':'36pt'}))
		odt.automaticstyles.addElement(titlestyle)
		titlespan = Span(stylename=titlestyle, text=_('Requirements for "%s"') % title)
		p = P(text='')
		p.addElement(titlespan)
		odt.text.addElement(p)
예제 #30
0
def copyStyle(style, autoStylesCache):
    autoStylesCache['lastIndex'] = autoStylesCache['lastIndex'] + 1
    cloneName = 'ce%d' % autoStylesCache['lastIndex']
    logger.debug('copy style : %s -> %s' % (style.getAttrNS(STYLENS, 'name'), cloneName))
    
    # Create the clone
    cloneStyle = Style(name=cloneName,family="table-cell")
    for node in style.childNodes:
        newNode = copy.copy(node)
        newNode.parentNode = None
        cloneStyle.appendChild(newNode)
    
    # Save the clone into the cache
    autoStylesCache['root'].addElement(cloneStyle)
    autoStylesCache['styles'][cloneName] = cloneStyle
    
    return cloneStyle
예제 #31
0
def extract_highlight_odf(name, img_quality, two_col, output_folder=None):
    textdoc = OpenDocumentText()
    doc_mask = fitzopen(name)
    doc_text = fitzopen(name)
    nb_pages = doc_text.pageCount
    #create style for paragraph
    style_p = Style(name="P1", family="paragraph", parentstylename="Standard")
    p_prop = ParagraphProperties(textalign="justify",
                                 justifysingleword="false")
    style_p.addElement(p_prop)
    textdoc.automaticstyles.addElement(style_p)

    #create style for images
    style_i = Style(name="fr1", family="graphic", parentstylename="Graphics")
    i_prop = GraphicProperties(wrap="none",
                               runthrough="foreground",
                               horizontalpos="center",
                               horizontalrel="paragraph")
    style_i.addElement(i_prop)
    textdoc.automaticstyles.addElement(style_i)

    #insert pdf file name
    textdoc.text.addElement(P(stylename=style_p, text=f"{name}\n\n"))

    #isolate highlights in _mask and text in _text
    doc_mask, doc_text = Page_Get_Highlights(doc_mask, doc_text)

    #iterate over pages to create rectangles to extract
    for i in range(nb_pages):

        if two_col == True:
            #colonnes
            for col in [1, 2]:
                rect, hierarchy, Xrects = Page_Get_Rects(doc_mask[i], col)

                if rect.shape[0] > 0:
                    textdoc = Page_Rect_get_Text_odf(doc_text, i, rect,
                                                     hierarchy, Xrects,
                                                     textdoc, style_p, style_i,
                                                     img_quality, col)
        else:
            col = 0
            rect, hierarchy, Xrects = Page_Get_Rects(doc_mask[i], col)
            if rect.shape[0] > 0:
                textdoc = Page_Rect_get_Text_odf(doc_text, i, rect, hierarchy,
                                                 Xrects, textdoc, style_p,
                                                 style_i, img_quality, col)
    if output_folder is not None:
        basename = os.path.basename(name)
        outname = basename.replace(".pdf", ".odt")
        outname = os.path.join(output_folder, outname)
        textdoc.save(outname)
    else:
        textdoc.save(name.replace(".pdf", ".odt"))
    doc_mask.close()
    doc_text.close()
예제 #32
0
def inittable(textdoc):
    # Create a style for the table content. One we can modify
    # later in the word processor.
    tablecontents = Style(name="Table Contents", family="paragraph")
    tablecontents.addElement(
        ParagraphProperties(numberlines="false", linenumber="0"))
    tablecontents.addElement(TextProperties(fontweight="bold"))
    textdoc.styles.addElement(tablecontents)
    widewidth = Style(name="co1", family="table-column")
    widewidth.addElement(
        TableColumnProperties(columnwidth="9", breakbefore="auto"))
    textdoc.automaticstyles.addElement(widewidth)
    textdoc.styles.addElement(widewidth)
    table = Table(name='test')
    table.addElement(
        TableColumn(stylename=widewidth, defaultcellstylename="ce1"))
    return table, tablecontents, textdoc
예제 #33
0
	def add_attribute_row(self, table, key, value):
		""" Add a two cell row to the table """
		boldstyle = Style(name="Bold",family="text")
		boldstyle.addElement(TextProperties(attributes={'fontweight':"bold"}))

		title_span = Span(stylename=boldstyle, text=key)
		pt = P(text='')
		pt.addElement(title_span)

		tr = TableRow()
		tc = TableCell(valuetype='string')
		tc.addElement(pt)
		tr.addElement(tc)
		tc = TableCell(valuetype='string')
		tc.addElement(P(text=value))
		tr.addElement(tc)
		table.addElement(tr)
예제 #34
0
    def save_test(self):
        new_partition = OpenDocumentText()

        T5style = Style(name="T5", family="text")
        T5style.addElement(TextProperties(fontname="Arial"))
        new_partition.automaticstyles.addElement(T5style)

        for i in range(len(self.allText)):
            old_text = teletype.extractText(self.allText[i])
            p = text.P(text="", stylename="T5")
            for j in range(len(old_text)):
                if (old_text[j] == " " and i in self.lignes):
                    p.addElement(Span(text=' ', stylename='T5'))
                else:
                    p.addText(old_text[j])

            new_partition.text.addElement(p)
        new_partition.save("x_test.odt")
예제 #35
0
def copyStyle(style, autoStylesCache):
    autoStylesCache['lastIndex'] = autoStylesCache['lastIndex'] + 1
    cloneName = 'ce%d' % autoStylesCache['lastIndex']
    logger.debug('copy style : %s -> %s' %
                 (style.getAttrNS(STYLENS, 'name'), cloneName))

    # Create the clone
    cloneStyle = Style(name=cloneName, family="table-cell")
    for node in style.childNodes:
        newNode = copy.copy(node)
        newNode.parentNode = None
        cloneStyle.appendChild(newNode)

    # Save the clone into the cache
    autoStylesCache['root'].addElement(cloneStyle)
    autoStylesCache['styles'][cloneName] = cloneStyle

    return cloneStyle
예제 #36
0
    def __setHeadingStyle(self):
        HdgStyle = Style(name="Heading", family='paragraph', parentstylename="Standard")
        HdgStyle.addElement(TextProperties(
                            fontweight='bold',
                            fontfamily='FreeSans',
                            fontsize='120%'))
        self.__doc.styles.addElement(HdgStyle)

        ''' Heading 1 '''
        HdgStyle = Style(name="Heading_20_1", family='paragraph', parentstylename="Heading")
        HdgStyle.addElement(TextProperties(fontsize='120%'))
        self.__doc.styles.addElement(HdgStyle)

        ''' Heading 2 '''
        HdgStyle = Style(name='Heading_20_2', family='paragraph', parentstylename='Heading')
        HdgStyle.addElement(TextProperties(fontsize='110%', color='#808080'))
        self.__doc.styles.addElement(HdgStyle)
예제 #37
0
	def generate(self, target_file):
		""" List each requirement and it's details """

		repo_dir = get_repo_dir()

		project = ProjectConfig()
		project.load_config_from_file(os.path.join(repo_dir, 'project.conf'))

		rt = RequirementTree()
		rt.load_repository(repo_dir)
		template_file = 'requirement-list-template.odt'

		# If no template found, then create new file
		try:
			template_file_path = os.path.join('templates', template_file)
			template_file_path = os.path.join(repo_dir, template_file_path)
			odt = odf.opendocument.load(template_file_path)
		except Exception as e:
			odt = odf.opendocument.OpenDocumentText()

		if project.name:
			odt.meta.addElement(odf.dc.Title(text=project.name))
		else:
			odt.meta.addElement(odf.dc.Title(text='[Set name in project.conf]'))

		if project.description:
			odt.meta.addElement(odf.dc.Description(text=project.description))

		# Add styles
		rejected = Style(name="Rejected", family="text")
		rejected.addElement(TextProperties(color="#666666", textlinethroughstyle="solid"))
		odt.automaticstyles.addElement(rejected)
		notrejected = Style(name="Not rejected", family="text")
		odt.automaticstyles.addElement(notrejected)

		self.write_child_details(rt, 1, rt, odt)

		try:
			odt.save(target_file, True)
		except:
			report_error(1, 'Unable to write to "%s", is file open?' % target_file)
예제 #38
0
파일: odt.py 프로젝트: yuhsianglin/HimalCo
def odt_write(object, filename, introduction=None, lmf2odt=lmf_to_odt, items=lambda lexical_entry: lexical_entry.get_lexeme(), sort_order=None, paradigms=False, reverse=False):
    """! @brief Write a document file.
    @param object The LMF instance to convert into document output format.
    @param filename The name of the document file to write with full path, for instance 'user/output.odt'.
    @param introduction The name of the text file with full path containing the introduction of the document, for instance 'user/config/introduction.txt'. Default value is None.
    @param lmf2odt A function giving the mapping from LMF representation information that must be written to ODT commands, in a defined order. Default value is 'lmf_to_odt' function defined in 'pylmflib/config/odt.py'. Please refer to it as an example.
    @param items Lambda function giving the item to sort. Default value is 'lambda lexical_entry: lexical_entry.get_lexeme()', which means that the items to sort are lexemes.
    @param sort_order Python list. Default value is 'None', which means that the document output is alphabetically ordered.
    @param paradigms A boolean value to introduce paradigms in document or not.
    @param reverse A boolean value to set if a reverse dictionary is wanted.
    """
    import string
    if sort_order is None:
        # Lowercase and uppercase letters must have the same rank
        sort_order = dict([(c, ord(c)) for c in string.lowercase])
        up = dict([(c, ord(c) + 32) for c in string.uppercase])
        sort_order.update(up)
        sort_order.update({'':0, ' ':0})
    textdoc = OpenDocumentText()
    # Styles
    s = textdoc.styles
    h1style = Style(name="Heading 1", family="paragraph")
    h1style.addElement(TextProperties(attributes={'fontsize':"24pt", 'fontweight':"bold" }))
    s.addElement(h1style)
    # An automatic style
    boldstyle = Style(name="Bold", family="text")
    boldprop = TextProperties(fontweight="bold", fontname="Arial", fontsize="8pt")
    boldstyle.addElement(boldprop)
    textdoc.automaticstyles.addElement(boldstyle)
    # Parse LMF values
    if object.__class__.__name__ == "LexicalResource":
        for lexicon in object.get_lexicons():
            # Document title
            h = H(outlinelevel=1, stylename=h1style, text=lexicon.get_id())
            textdoc.text.addElement(h)
            # Plain paragraph
            p = P(text=lexicon.get_label())
            # Text
            boldpart = Span(stylename=boldstyle, text="Test. ")
            p.addElement(boldpart)
            # Introduction
            if introduction is not None:
                p.addText(file_read(introduction))
                textdoc.text.addElement(p)
            # Page break
            #
            # Text body
            lmf2odt(lexicon, textdoc, items, sort_order, paradigms, reverse)
    else:
        raise OutputError(object, "Object to write must be a Lexical Resource.")
    textdoc.save(filename)
예제 #39
0
    def createTargetFormat(self, metricValues: Dict[str, List[int]],
                           metricLabels: List[str]) -> bytes:
        textdoc = OpenDocumentSpreadsheet()
        tablecontents = Style(name="Table Contents", family="paragraph")
        tablecontents.addElement(
            ParagraphProperties(numberlines="false", linenumber="0"))
        tablecontents.addElement(TextProperties(fontweight="bold"))
        textdoc.styles.addElement(tablecontents)

        table = Table(name="Java Metrics")

        tr = self.newRow(table)
        for metricLabel in metricLabels:
            self.addElementToRow(metricLabel, "string", tr, tablecontents)

        for methodName in metricValues.keys():
            tr = self.newRow(table)
            self.addElementToRow(methodName, "string", tr, tablecontents)

            for metricValue in metricValues[methodName]:
                self.addElementToRow(str(metricValue), "float", tr,
                                     tablecontents)

        textdoc.spreadsheet.addElement(table)

        stringOutput = BytesIO()
        textdoc.write(stringOutput)
        return stringOutput.getvalue()
예제 #40
0
    def createFinalReportTargetFormat(self, finalReport: List[list]) -> bytes:
        textdoc = OpenDocumentSpreadsheet()
        tablecontents = Style(name="Table Contents", family="paragraph")
        tablecontents.addElement(
            ParagraphProperties(numberlines="false", linenumber="0"))
        tablecontents.addElement(TextProperties(fontweight="bold"))
        textdoc.styles.addElement(tablecontents)

        table = Table(name="Java Metrics")

        tr = self.newRow(table)
        for columnLabels in finalReport[0]:
            self.addElementToRow(columnLabels, "string", tr, tablecontents)

        for row in finalReport[1:]:
            tr = self.newRow(table)
            self.addElementToRow(row[0], "string", tr, tablecontents)
            self.addElementToRow(row[1], "string", tr, tablecontents)

            for element in row[2:]:
                self.addElementToRow(str(element), "float", tr, tablecontents)

        textdoc.spreadsheet.addElement(table)

        stringOutput = BytesIO()
        textdoc.write(stringOutput)
        return stringOutput.getvalue()
예제 #41
0
    def test_percentage(self):
        """ Test that an automatic style can refer to a PercentageStyle as a datastylename """
        doc = OpenDocumentSpreadsheet()
        nonze = PercentageStyle(name='N11')
        nonze.addElement(Number(decimalplaces='2', minintegerdigits='1'))
        nonze.addElement(Text(text='%'))
        doc.automaticstyles.addElement(nonze)
        pourcent = Style(name='pourcent',
                         family='table-cell',
                         datastylename='N11')
        pourcent.addElement(ParagraphProperties(textalign='center'))
        pourcent.addElement(
            TextProperties(attributes={
                'fontsize': "10pt",
                'fontweight': "bold",
                'color': "#000000"
            }))
        doc.automaticstyles.addElement(pourcent)

        table = Table(name='sheet1')
        tr = TableRow()
        tc = TableCell(formula='=AVERAGE(C4:CB62)/2',
                       stylename='pourcent',
                       valuetype='percentage')
        tr.addElement(tc)
        table.addElement(tr)
        doc.spreadsheet.addElement(table)
        doc.save(u"TEST.ods")
        self.saved = True
        d = load(u"TEST.ods")
        result = d.contentxml()  # contentxml is supposed to yeld a bytes
        self.assertNotEqual(-1, result.find(b'''<number:percentage-style'''))
        self.assertNotEqual(-1,
                            result.find(b'''style:data-style-name="N11"'''))
        self.assertNotEqual(-1, result.find(b'''style:name="pourcent"'''))
예제 #42
0
class OdtConverter(Converter):
    def __init__(self, output_file_name):
        self._document = OpenDocumentText()
        self._raw_document_content = []
        self._output_file_path = "target/{}.odt".format(output_file_name)
        self._h1_style = None
        self._p_style = None

    def convert(self):
        self._generate_styles()
        sources = self._process_input_files()
        for source in sources:
            self._raw_document_content += source
        self._process_raw_document_content()
        self._document.save(self._output_file_path)

    def _generate_styles(self):
        self._h1_style = Style(name="Heading 1", family="paragraph")
        self._h1_style.addElement(ParagraphProperties(attributes={"margintop": "24pt", "marginbottom": "12pt",
                                                                  "keepwithnext": "always"}))
        self._h1_style.addElement(TextProperties(attributes={"fontsize": "16pt"}))
        self._document.styles.addElement(self._h1_style)
        self._p_style = Style(name="Body", family="paragraph")
        self._p_style.addElement(ParagraphProperties(attributes={"textindent": "1.25cm", "textalign": "justify",
                                                                 "orphans": 2, "widows": 2}))
        self._document.styles.addElement(self._p_style)

    def _process_raw_document_content(self):
        for line in self._raw_document_content:
            if line.startswith("# "):
                new_element = H(outlinelevel=1, stylename=self._h1_style, text=line.replace("# ", ""))
            else:
                new_element = P(text=line, stylename=self._p_style)
            self._document.text.addElement(new_element)
예제 #43
0
    def __init__(self, filename=None):
        self.doc = OpenDocumentSpreadsheet()
        self.filename = filename

        # Add some common styles
        self.tablecontents = Style(name="Table Contents", family="paragraph")
        self.tablecontents.addElement(
            ParagraphProperties(numberlines="false", linenumber="0"))
        self.doc.styles.addElement(self.tablecontents)

        self.currencystyle = self._add_currencystyle()

        self.boldcurrencystyle = Style(name="BoldPounds",
                                       family="table-cell",
                                       parentstylename=self.currencystyle)
        self.boldcurrencystyle.addElement(TextProperties(fontweight="bold"))
        self.doc.styles.addElement(self.boldcurrencystyle)

        self.boldtextstyle = Style(name="BoldText",
                                   family="table-cell",
                                   parentstylename=self.tablecontents)
        self.boldtextstyle.addElement(TextProperties(fontweight="bold"))
        self.doc.styles.addElement(self.boldtextstyle)

        self._widthstyles = {}
예제 #44
0
파일: odsmod.py 프로젝트: chiefexb/fnscheck
def inittable(textdoc):
 # Create a style for the table content. One we can modify
 # later in the word processor.
 tablecontents = Style(name="Table Contents", family="paragraph")
 tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0"))
 tablecontents.addElement(TextProperties(fontweight="bold"))
 textdoc.styles.addElement(tablecontents)
 widewidth = Style(name="co1", family="table-column")
 widewidth.addElement(TableColumnProperties(columnwidth="9", breakbefore="auto"))
 textdoc.automaticstyles.addElement(widewidth)
 textdoc.styles.addElement(widewidth)
 table = Table( name='test' )
 table.addElement(TableColumn(stylename=widewidth, defaultcellstylename="ce1"))
 return table,tablecontents,textdoc
예제 #45
0
def export_ods (headers, data):
    doc = OpenDocumentSpreadsheet()
    style = Style(name="Large number", family="table-cell")
    style.addElement(TextProperties(fontfamily="Arial", fontsize="15pt"))
    doc.styles.addElement(style)
    widewidth = Style(name="co1", family="table-column")
    widewidth.addElement(TableColumnProperties(columnwidth="2.8cm", breakbefore="auto"))
    doc.automaticstyles.addElement(widewidth)

    table = Table()
    if len (headers) > 0:
        tr = TableRow ()
        table.addElement (tr)
        for item in headers:
            tc = TableCell ()
            tr.addElement (tc)
            p = P(stylename = style, text = txt(item))
            tc.addElement (p)

    for line in data:
        tr = TableRow ()
        table.addElement (tr)
        for item in line:
            tc = TableCell ()
            tr.addElement (tc)
            p = P (stylename = style, text = txt(item))
            tc.addElement (p)

    doc.spreadsheet.addElement(table)
    buffer = StringIO ()
    doc.write(buffer)

    return buffer.getvalue ()
예제 #46
0
 def _add_currencystyle(self, name="Pounds"):
     """Construct a currency style"""
     cs = number.CurrencyStyle(name=name)
     symbol = number.CurrencySymbol(language="en", country="GB")
     symbol.addText("£")
     cs.addElement(symbol)
     n = number.Number(decimalplaces=2, minintegerdigits=1, grouping="true")
     cs.addElement(n)
     self.doc.styles.addElement(cs)
     currencystyle = Style(name=name, family="table-cell",
                           parentstylename="Default", datastylename=name)
     self.doc.styles.addElement(currencystyle)
     return currencystyle
예제 #47
0
 def _add_headerstyle(self):
     header = Style(name="ColumnHeader", family="table-cell")
     header.addElement(
         ParagraphProperties(textalign="center"))
     header.addElement(
         TextProperties(fontweight="bold"))
     self.doc.styles.addElement(header)
     return header
예제 #48
0
 def addParagraphStyle(self, id, name, paragraph_properties={}, text_properties={}, graphic_properties={}):
     style = Style(name=name, family="paragraph")
     if len(paragraph_properties)>0:
         style.addElement(ParagraphProperties(**paragraph_properties))
     if len(text_properties)>0:
         style.addElement(TextProperties(**text_properties))
     setattr(self, id, style)
     self.document.styles.addElement(style)
예제 #49
0
    def __init__(self, filename=None):
        self.doc = OpenDocumentSpreadsheet()
        self.filename = filename

        # Add some common styles
        self.tablecontents = Style(name="Table Contents", family="paragraph")
        self.tablecontents.addElement(
            ParagraphProperties(numberlines="false", linenumber="0"))
        self.doc.styles.addElement(self.tablecontents)

        self.currencystyle = self._add_currencystyle()

        self.boldcurrencystyle = Style(name="BoldPounds", family="table-cell",
                                       parentstylename=self.currencystyle)
        self.boldcurrencystyle.addElement(
            TextProperties(fontweight="bold"))
        self.doc.styles.addElement(self.boldcurrencystyle)

        self.boldtextstyle = Style(name="BoldText", family="table-cell",
                                   parentstylename=self.tablecontents)
        self.boldtextstyle.addElement(TextProperties(fontweight="bold"))
        self.doc.styles.addElement(self.boldtextstyle)

        self._widthstyles = {}
예제 #50
0
def writer(data, **kwargs):
    """
    Liberally adapted from odfpy's csv2ods script.
    """
    def handle_formula(f):
        return TableCell(valuetype="float", formula="{}".format(f))

    textdoc = OpenDocumentSpreadsheet(**kwargs)
    # Create a style for the table content. One we can modify
    # later in the word processor.
    tablecontents = Style(name="Table Contents", family="paragraph")
    tablecontents.addElement(
        ParagraphProperties(numberlines="false", linenumber="0"))
    tablecontents.addElement(TextProperties(fontweight="bold"))
    textdoc.styles.addElement(tablecontents)

    # Start the table
    table = Table(name=u'Sheet 1')
    fltExp = re.compile('^\s*[-+]?\d+(\.\d+)?\s*$')

    for row in data:
        tr = TableRow()
        table.addElement(tr)
        for val in row:
            if isinstance(val, spreadsheet.Formula):
                tc = handle_formula(val)
            else:
                valuetype = 'string'
                if not isinstance(val, unicode):
                    if isinstance(val, str):
                        text_value = "{}".format(val, PWENC, 'replace')
                    else:
                        text_value = "{}".format(val)
                else:
                    text_value = val

                if isinstance(val, (float, int, long)) or (isinstance(
                        val, str) and fltExp.match(text_value)):
                    valuetype = 'float'

                if valuetype == 'float':
                    tc = TableCell(valuetype="float", value=text_value.strip())
                else:
                    tc = TableCell(valuetype=valuetype)

                if val is not None:
                    p = P(stylename=tablecontents, text=text_value)
                    tc.addElement(p)

            tr.addElement(tc)

    textdoc.spreadsheet.addElement(table)

    result = StringIO()
    textdoc.write(result)
    return result.getvalue()
예제 #51
0
def count_height(row, cell):
    """Counting height that shows all text in cell.

    This functions uses width of text-column and font size.

    Args:
        row - current row.
        cell - current cell.

    """
    style_name = cell.getAttribute('stylename')
    try:
        style = saved_styles[style_name]
        text_prop = style.getElementsByType(TextProperties)
        try:
            text_prop = text_prop[0]
            font_size = str(text_prop.getAttribute('fontsize'))
            font_size = font_size.replace('pt', '')
            font_size = int(font_size)
        except IndexError:
            font_size = 10
    except KeyError:
        font_size = 10

    symbols_in_string = PTINTENCM // font_size + 1
    length = 0
    for p in cell.getElementsByType(P):
        length += len(p.__str__())
    height = font_size * (length // symbols_in_string + 1) + 4
    height = str(height) + 'pt'
    new_name = 'heightsuit' + height
    height_suit = Style(name=new_name, family='table-row')
    height_suit.addElement(TableRowProperties(rowheight=height))

    ods.automaticstyles.addElement(height_suit)
    row.setAttribute(attr='stylename', value=new_name)
def label(an_odt, a_spice, a_font):
	label_stylename = a_spice + a_font
	label_graphic_style = Style(name=label_stylename, family="graphic")
	label_graphic_properties = GraphicProperties()
	label_graphic_style.addElement(label_graphic_properties)
	label_beehive = beehive(an_odt, label_graphic_style,
							"5mm", "50mm", "60mm", "263mm", "1")
	label_frame = label_beehive["frame"]
	label_textbox = label_beehive["textbox"]

	## textgraph
	label_stylename = a_spice + a_font
	label_textgraph_style = Style(name=label_stylename, family="paragraph")
	label_text_props = TextProperties(fontsize="11.1pt", fontfamily="Nimbus Sans L", color="#ffffff")
	label_textgraph_style.addElement(label_text_props)
	label_paragraph_props = ParagraphProperties(backgroundcolor="#000000", textalign="center")
	label_textgraph_style.addElement(label_paragraph_props)
	an_odt.styles.addElement(label_textgraph_style)

	text_unit(an_odt, label_textgraph_style, a_spice + " " + a_font, label_textbox)

	an_odt.text.addElement(label_frame)
예제 #53
0
 def _create_styles( self ):
     #Creating new ruby style
     self.ruby_style_name = "RubyMy"
     my_ruby_style = Style( name=self.ruby_style_name, family="ruby" )
     my_ruby_style.addElement( 
         RubyProperties( rubyalign = "center", 
                         rubyposition = "above" ) )
     self.doc.automaticstyles.addElement( my_ruby_style )
     
     #Create dotted style
     self.dot_style_name = "DottedMy"
     my_dotted_style = Style( name = self.dot_style_name, 
                              family="text" )
     my_dotted_style.addElement(
         TextProperties( textemphasize="dot above" ) )
     self.doc.automaticstyles.addElement( my_dotted_style )
def dingbat_spices(an_odt, a_spice, a_font):
	## graphic
	dingbat_stylename = a_spice + "_style_frame"
	dingbat_graphic_style = Style(name=dingbat_stylename, family="graphic")
	dingbat_graphic_properties = GraphicProperties()
	dingbat_graphic_style.addElement(dingbat_graphic_properties)
	dingbat_beehive = beehive(an_odt, dingbat_graphic_style,
							"240mm", "10mm", "0mm", "0mm", "100")
	dingbat_frame = dingbat_beehive["frame"]
	dingbat_textbox = dingbat_beehive["textbox"]

	## textgraph
	dingbat_stylename = a_spice + "_style_paragraph"
	dingbat_textgraph_style = Style(name=dingbat_stylename, family="paragraph")
	dingbat_text_props = TextProperties(fontsize="14pt", fontfamily="FreeSerif")
	dingbat_textgraph_style.addElement(dingbat_text_props)
	dingbat_paragraph_props = ParagraphProperties()
	dingbat_textgraph_style.addElement(dingbat_paragraph_props)
	an_odt.styles.addElement(dingbat_textgraph_style)

	for i in dingbats[a_spice]:
		text_unit(an_odt, dingbat_textgraph_style, i, dingbat_textbox)

	an_odt.text.addElement(dingbat_frame)
예제 #55
0
 def __init__(self, name):
     self.name = name
     self.document = OpenDocumentText()
     self.current_page = None
     self.photo_style = Style(name="Photo", family="graphic")
     self.document.styles.addElement(self.photo_style)
     self.font_styles = []
     self.page_layouts = []
     self.page_masters = []
     self.page_styles = []
     self.temp_images = []
     frame_style = Style(name="FrameStyle", family="graphic")
     frame_style.addElement(GraphicProperties(borderlinewidth="none"))
     self.document.styles.addElement(frame_style)
     frame_style_rotated = Style(name="FrameStyleRotated", family="graphic")
     frame_style_rotated.addElement(
         GraphicProperties(fill="none", stroke="none", verticalpos="from-top", verticalrel="paragraph")
     )
     self.document.automaticstyles.addElement(frame_style_rotated)
def make_document():
    # Create the document
    doc = OpenDocumentDrawing()

    # Create the drawing page
    dpstyle = Style(family="drawing-page", name="DP1")
    dpstyle.addElement(DrawingPageProperties(backgroundsize="border",
                                             fill="none"))
    doc.automaticstyles.addElement(dpstyle)

    # Create page layout specifying dimensions
    plstyle = PageLayout(name="PM1")
    plstyle.addElement(PageLayoutProperties(margin="1in", pageheight="8.5in", pagewidth="11in", printorientation="landscape"))
    doc.automaticstyles.addElement(plstyle)

    # Create a master page
    masterpage = MasterPage(stylename=dpstyle, name="Default", pagelayoutname=plstyle)
    doc.masterstyles.addElement(masterpage)

    # Create a page to contain the drawing
    drawpage = Page(masterpagename=masterpage, name="page1", stylename=dpstyle)
    doc.drawing.addElement(drawpage)

    # Create a style for the circles
    circlestyle = Style(family="graphic", name="solid")
    circlestyle.addElement(
        GraphicProperties(fill="none", stroke="#000000", strokewidth="0.01in"))
    doc.automaticstyles.addElement(circlestyle)

    group=G()
    drawpage.addElement(group)

    circlePlotter = CirclePlotter(circlestyle)
    
    #nestedTriangle = NestedTriangle(group, circlePlotter, 0.25, 0.5, 0.5)
    #nestedTriangle = NestedTriangle(group, circlePlotter, 0.125, 0.75, 0.5)
    nestedTriangle = NestedTriangle(group, circlePlotter, 0.19, 0.625, 0.39)
    nestedTriangle.draw(5.5, 4.25, 3.5, 6)


    # Save the work
    doc.save(DRAWING_FILE, True)
예제 #57
0
파일: sqlite2ods.py 프로젝트: BrickXu/odfpy
import sqlite
from odf.opendocument import OpenDocumentSpreadsheet
from odf.style import Style, TextProperties, ParagraphProperties, TableColumnProperties
from odf.text import P
from odf.table import Table, TableColumn, TableRow, TableCell

if len(sys.argv) != 3:
    print "Usage: sqlite-db table"
    sys.exit(2)

sqldb = sys.argv[1]
sqltable = sys.argv[2]
textdoc = OpenDocumentSpreadsheet()
# Create a style for the table content. One we can modify
# later in the word processor.
tablecontents = Style(name="Table Contents", family="paragraph")
tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0"))
#tablecontents.addElement(TextProperties(fontweight="bold"))
textdoc.styles.addElement(tablecontents)

# Create automatic styles for the column widths.
# We want two different widths, one in inches, the other one in metric.
# ODF Standard section 15.9.1
widthshort = Style(name="Wshort", family="table-column")
widthshort.addElement(TableColumnProperties(columnwidth="1.7cm"))
textdoc.automaticstyles.addElement(widthshort)

widthwide = Style(name="Wwide", family="table-column")
widthwide.addElement(TableColumnProperties(columnwidth="1.5in"))
textdoc.automaticstyles.addElement(widthwide)
예제 #58
0
from odf.opendocument import OpenDocumentText
from odf.text import P
from odf.style import Style, MasterPage, PageLayout, PageLayoutProperties, TextProperties, GraphicProperties, ParagraphProperties, DrawingPageProperties, BackgroundImage
from odf.draw import Page, Frame, TextBox, Image

doc = OpenDocumentText()

graphicStyleA = Style(name="graphicstyleA", family="graphic")
gpA = GraphicProperties(border="1cm double #000000", padding="1cm", backgroundcolor="#cccccc")
graphicStyleA.addElement(gpA)

textStyleA = Style(name="textstyleA", family="paragraph")
tpA = TextProperties(fontsize="16pt", fontfamily="Limousine")
textStyleA.addElement(tpA)
ppA = ParagraphProperties(textalign="right")
textStyleA.addElement(ppA)

graphicStyleB = Style(name="graphicstyleB", family="graphic")
gpB = GraphicProperties(border="1cm double #000000", padding="1cm", backgroundcolor="#ff0000")
graphicStyleB.addElement(gpB)

textStyleB = Style(name="textstyleB", family="paragraph")
tpB = TextProperties(fontsize="16pt", fontfamily="diluvienne")
textStyleB.addElement(tpB)

frameA = Frame(stylename=graphicStyleA, height="15cm", width="10cm")
frameB = Frame(stylename=graphicStyleB, height="10cm", width="15cm")

doc.styles.addElement(graphicStyleA)
doc.styles.addElement(textStyleA)
예제 #59
0
def do_job(job):

    warnings = get_warnings(job['sts'], job['ets'], job['wfo'], job['wtype'])

    os.makedirs("/tmp/%s" % (job['jobid'],))
    os.chdir("/tmp/%s" % (job['jobid'],))
    
    basefn = "%s-%s-%s-%s-%s" % (job['wfo'], job['wtype'].replace(",", "_"), 
                                 job['radar'], job['sts'].strftime("%Y%m%d%H"),
                                      job['ets'].strftime("%Y%m%d%H"))
    outputfile = "%s.odp" % (basefn,)

    doc = OpenDocumentPresentation()

    # We must describe the dimensions of the page
    pagelayout = PageLayout(name="MyLayout")
    doc.automaticstyles.addElement(pagelayout)
    pagelayout.addElement(PageLayoutProperties(margin="0pt", pagewidth="800pt",
        pageheight="600pt", printorientation="landscape"))

    # Style for the title frame of the page
    # We set a centered 34pt font with yellowish background
    titlestyle = Style(name="MyMaster-title2", family="presentation")
    titlestyle.addElement(ParagraphProperties(textalign="center"))
    titlestyle.addElement(TextProperties(fontsize="34pt"))
    titlestyle.addElement(GraphicProperties(fillcolor="#ffff99"))
    doc.styles.addElement(titlestyle)

    # Style for the title frame of the page
    # We set a centered 34pt font with yellowish background
    indexstyle = Style(name="MyMaster-title", family="presentation")
    indexstyle.addElement(ParagraphProperties(textalign="center"))
    indexstyle.addElement(TextProperties(fontsize="28pt"))
    indexstyle.addElement(GraphicProperties(fillcolor="#ffffff",
                                            stroke="none"))
    doc.styles.addElement(indexstyle)

    # Style for the photo frame
    photostyle = Style(name="MyMaster-photo", family="presentation")
    doc.styles.addElement(photostyle)

    # Every drawing page must have a master page assigned to it.
    masterpage = MasterPage(name="MyMaster", pagelayoutname=pagelayout)
    doc.masterstyles.addElement(masterpage)

    dpstyle = Style(name="dp1", family="drawing-page")
    #dpstyle.addElement(DrawingPageProperties(transitiontype="automatic",
    #   transitionstyle="move-from-top", duration="PT5S"))
    doc.automaticstyles.addElement(dpstyle)
    
    # Title slide
    page = Page(masterpagename=masterpage)
    doc.presentation.addElement(page)
    frame = Frame(stylename=indexstyle, width="720pt", height="500pt", 
                  x="40pt", y="10pt")
    page.addElement( frame )
    textbox = TextBox()
    frame.addElement(textbox)
    textbox.addElement(P(text="IEM Raccoon Report"))
    
    frame = Frame(stylename=indexstyle, width="720pt", height="500pt", 
                  x="40pt", y="150pt")
    page.addElement( frame )
    textbox = TextBox()
    frame.addElement(textbox)
    textbox.addElement(P(text="WFO: %s" % (job['wfo'],)))
    textbox.addElement(P(text="Radar: %s Product: %s" % (job['radar'], job['nexrad_product'])))
    textbox.addElement(P(text="Phenomenas: %s" % (job['wtype'], )))
    textbox.addElement(P(text="Start Time: %s UTC" % (job['sts'].strftime("%d %b %Y %H"),)))
    textbox.addElement(P(text="End Time: %s UTC" % (job['ets'].strftime("%d %b %Y %H"),)))
    textbox.addElement(P(text=""))
    textbox.addElement(P(text="Raccoon Version: %s" % (__REV__,)))
    textbox.addElement(P(text="Generated on: %s" % (
                                    datetime.datetime.utcnow().strftime("%d %b %Y %H:%M %Z"))))
    textbox.addElement(P(text=""))
    textbox.addElement(P(text="Bugs/Comments/Yelling?: daryl herzmann [email protected]"))
    
    
    i = 0
    for warning in warnings:
        # Make Index page for the warning
        page = Page(masterpagename=masterpage)
        doc.presentation.addElement(page)
        titleframe = Frame(stylename=indexstyle, width="700pt", height="500pt", 
                       x="10pt", y="10pt")
        page.addElement(titleframe)
        textbox = TextBox()
        titleframe.addElement(textbox)
        textbox.addElement(P(text="%s.O.NEW.K%s.%s.W.%04i" % ( 
                                    job['sts'].year, job['wfo'],
                                warning['phenomena'],warning['eventid'])))
        textbox.addElement(P(text="Issue: %s UTC" % ( 
                                    warning['issue'].strftime("%d %b %Y %H:%M"),)))
        textbox.addElement(P(text="Expire: %s UTC" % ( 
                                    warning['expire'].strftime("%d %b %Y %H:%M"),)))
        textbox.addElement(P(text="Poly Area: %.1f sq km (%.1f sq mi) [%.1f%% vs County]" % ( 
                                    warning['polyarea'], warning['polyarea'] * 0.386102,
                                    warning['polyarea'] / warning['countyarea'] * 100.0)))
        textbox.addElement(P(text="County Area: %.1f square km (%.1f square miles)" % ( 
                                    warning['countyarea'], warning['countyarea'] * 0.386102)))
        
        url = "http://iem21.local/GIS/radmap.php?"
        url += "layers[]=places&layers[]=legend&layers[]=ci&layers[]=cbw&layers[]=sbw"
        url += "&layers[]=uscounties&layers[]=bufferedlsr&lsrbuffer=15"
        url += "&vtec=%s.O.NEW.K%s.%s.W.%04i" % ( job['sts'].year, job['wfo'],
                                    warning['phenomena'],warning['eventid'])
        
        cmd = "wget -q -O %i.png '%s'" % (i, url)
        os.system(cmd)
        photoframe = Frame(stylename=photostyle, width="480pt", 
                               height="360pt", x="160pt", y="200pt")
        page.addElement(photoframe)
        href = doc.addPicture("%i.png" % (i,))
        photoframe.addElement(Image(href=href))
        i += 1
        
        times = []
        now = warning['issue']
        while now < warning['expire']:
            times.append( now )
            now += datetime.timedelta(minutes=15)
        times.append( warning['expire'] - datetime.timedelta(minutes=1))
        
        for now in times:    
            page = Page(stylename=dpstyle, masterpagename=masterpage)
            doc.presentation.addElement(page)
            titleframe = Frame(stylename=titlestyle, width="720pt", height="56pt", 
                           x="40pt", y="10pt")
            page.addElement(titleframe)
            textbox = TextBox()
            titleframe.addElement(textbox)
            textbox.addElement(P(text="%s.W.%04i Time: %s UTC" % ( 
                                    warning['phenomena'],warning['eventid'],
                                    now.strftime("%d %b %Y %H%M"))))
            
            if job['nexrad_product'] == 'N0U':
                if now < SUPER_RES:
                    n0qn0r = 'N0V'
                else:
                    n0qn0r = 'N0U'
            else:
                if now < SUPER_RES:
                    n0qn0r = 'N0R'
                else:
                    n0qn0r = 'N0Q'
            
            url = "http://iem21.local/GIS/radmap.php?"
            url += "layers[]=ridge&ridge_product=%s&ridge_radar=%s&" % (n0qn0r, 
                                                                job['radar'])
            url += "layers[]=sbw&layers[]=sbwh&layers[]=uscounties&"
            url += "layers[]=lsrs&ts2=%s&" % (
                    (now + datetime.timedelta(minutes=15)).strftime("%Y%m%d%H%M"),)
            url += "vtec=%s.O.NEW.K%s.%s.W.%04i&ts=%s" % ( job['sts'].year, job['wfo'],
                                    warning['phenomena'],warning['eventid'],
                                    now.strftime("%Y%m%d%H%M"))

            cmd = "wget -q -O %i.png '%s'" % (i, url)
            os.system(cmd)
            photoframe = Frame(stylename=photostyle, width="640pt", 
                               height="480pt", x="80pt", y="70pt")
            page.addElement(photoframe)
            href = doc.addPicture("%i.png" % (i,))
            photoframe.addElement(Image(href=href))
            i += 1

    doc.save(outputfile)
    del doc
    cmd = "unoconv -f ppt %s" % (outputfile,)
    os.system( cmd )
    print "%s.ppt" % (basefn,)
    if os.path.isfile("%s.ppt" % (basefn,)):
        print 'Here!'
        shutil.copyfile("%s.ppt" % (basefn,), "/mesonet/share/pickup/raccoon/%s.ppt" % (basefn,))