Example #1
0
 def testAddPicture(self):
     """ Check that AddPicture works"""
     THUMBNAILNAME = "thumbnail.png"
     icon = thumbnail.thumbnail()
     f = open(THUMBNAILNAME, "wb")
     f.write(icon)
     f.close()
     textdoc = OpenDocumentText()
     textdoc.addPicture(THUMBNAILNAME)
     os.unlink(THUMBNAILNAME)
Example #2
0
 def testAddPicture(self):
     """ Check that AddPicture works"""
     THUMBNAILNAME = "thumbnail.png"
     icon = thumbnail.thumbnail()
     f = open(THUMBNAILNAME, "wb")
     f.write(icon)
     f.close()
     textdoc = OpenDocumentText()
     textdoc.addPicture(THUMBNAILNAME)
     os.unlink(THUMBNAILNAME)
Example #3
0
        'D': ['Batx.2H', 'Batx.2I']
    }
})

courses = [
    '1 ESO', '2 ESO', '2º PMAR', '3 ESO', '3º PMAR', '4 ESO', '1º Bach.',
    '2º Bach.'
]
#courses = ['2º Bach.']

for k in courses:
    coursePage(k, coursegroups[k], lang)

title = H(stylename=h1style, text="Promoción", outlinelevel=1)
textdoc.text.addElement(title)
for k in courses:
    p = P()
    textdoc.text.addElement(p)
    img_path = path + k + "-allgroupsprom.png"
    href = textdoc.addPicture(img_path)
    f = Frame(name=k,
              anchortype="paragraph",
              width="17cm",
              height="7.5cm",
              zindex="0")
    p.addElement(f)
    img = Image(href=href, type="simple", show="embed", actuate="onLoad")
    f.addElement(img)

textdoc.save(period + year + "/report-" + period + year + "-" + lang + ".odt")
Example #4
0
class ODFWriter(object):
    ignoreUnknownNodes = True
    namedLinkCount = 1

    def __init__(self, env=None, status_callback=None, language="en", namespace="en.wikipedia.org", creator="", license="GFDL"):
        self.env = env
        self.status_callback = status_callback
        self.language = language
        self.namespace = namespace
        self.references = []
        self.doc =  OpenDocumentText()
        style.applyStylesToDoc(self.doc)
        self.text = self.doc.text
        self.namedLinkCount = 0
        self.conf = odfconf.OdfConf

        if creator:
            self.doc.meta.addElement(meta.InitialCreator(text=creator))
            self.doc.meta.addElement(dc.Creator(text=creator))
        if language is not None:
            self.doc.meta.addElement(dc.Language(text=language))
        if license is not None:
            self.doc.meta.addElement(meta.UserDefined(name="Rights", text=license))


    def writeTest(self, root):
        self.write(root, self.doc.text)

    def writeBook(self, book, output, removedArticlesFile=None, coverimage=None):
        """
        bookParseTree must be advtree and sent through preprocess()
        """
        
        if self.env and self.env.metabook:
            self.doc.meta.addElement(dc.Title(text=self.env.metabook.get("title", "")))
        #licenseArticle = self.env.metabook['source'].get('defaultarticlelicense','') # FIXME

        for e in book.children:
            self.write(e, self.doc.text)
        doc = self.getDoc()
        #doc.toXml("%s.odf.xml"%fn)
        doc.save(output, addsuffix=False)
        log( "writing to %r" % output )
        
    def getDoc(self, debuginfo=""):
        return self.doc

    def asstring(self, element = None):

        class Writer(object):
            def __init__(self):
                self.res = []
            def write(self, txt):
                if isinstance(txt, unicode):
                    self.res.append(str(txt))
                else:
                    self.res.append(txt)
            def getvalue(self):
                return "".join(self.res) 

        s = Writer()
        if not element:
            element = self.doc.text 
        element.toXml(0, s)
       
        return s.getvalue()

    def writeText(self, obj, parent):
        try:
            parent.addText(obj.caption)
        except odf.element.IllegalText:
            p = ParagraphProxy(stylename=style.textbody)
            try:
                parent.addElement(p)
                p.addText(obj.caption)
            except odf.element.IllegalChild:
                log("writeText:", obj, "not allowed in ", parent.type, "adding Paragraph failed")

    def write(self, obj, parent=None):
        assert parent is not None
  
        def saveAddChild(p,c):
            try:
                p.addElement(c) 
                assert c.parentNode is not None
                return True
            except odf.element.IllegalChild:
                # fails if paragraph in span:  odfwriter >> write: u'text:p' 'not allowed in ' u'text:span' ', dumping'
                try: # maybe c has no attribute type
                    art = obj.getParentNodesByClass(advtree.Article)[0]
                    log("in article ", art.caption)
                    log("write:", c.type, "not allowed in ", p.type, ", dumping")
                except AttributeError:
                    log("missing .type attribute %r %r " %(c, p))
                return False

        
        while hasattr(parent, "writeto"):
            parent = parent.writeto # SPECIAL HANDLING 

        # if its text, append to last node
        if isinstance(obj, parser.Text):
            self.writeText(obj, parent)
        else:
            # check for method
            m = "owrite" + obj.__class__.__name__
            m=getattr(self, m, None)
            
            if m: # find handler
                e = m(obj)
                
            elif self.ignoreUnknownNodes:
                log("Handler for node %s not found! SKIPPED" %obj.__class__.__name__)
                showNode(obj)
                e = None
            else:
                raise Exception("unknown node:%r" % obj)
            
            if isinstance(e, SkipChildren): # do not process children of this node
                if e.element is not None:
                    saveAddChild(parent, e.element)
                return # skip
            elif e is None:
                e = parent
            else:
                if not saveAddChild(parent, e):
                    return # 

            for c in obj.children[:]:
                self.write(c,e)


    def writeChildren(self, obj, parent): # use this to avoid bugs!
        "writes only the children of a node"
        for c in obj:
            self.write(c, parent)
            

    def owriteArticle(self, a):
        self.references = [] # collect references
        title = a.caption
        r = text.Section(stylename=style.sect, name=title) #, display="none")
        r.addElement(text.H(outlinelevel=1, stylename=style.ArticleHeader, text=title))
        return r 

    def owriteChapter(self, obj):
        text = obj.caption
        log("Unhandled Chapter %r" % obj) # FIXME

    def owriteSection(self, obj):
        hXstyles = (style.h0,style.h1,style.h2,style.h3,style.h4,style.h5)

        # skip empty sections (as for eg References)
        hasDisplayContent = u"".join(x.getAllDisplayText().strip() for x in obj.children [1:]) \
            or obj.getChildNodesByClass(advtree.ImageLink) # FIXME, add AdvancedNode.hasContent property
        enabled = False 
        if enabled and not hasDisplayContent:  # FIXME
            return SkipChildren()

        title = obj.children[0].getAllDisplayText()

        # = is level 0 as in article title = 
        # == is level 1 as in mediawiki top level section ==
        # getSectionLevel() == 1 for most outer section level
        level = 1 + obj.getSectionLevel() # min: 1+0 = 1
        level = min(level, len(hXstyles))
        hX = hXstyles[level-1] 

        r = text.Section(stylename=style.sect, name=title) 
        r.addElement(text.H(outlinelevel=level, stylename=hX, text=title))
        obj.children = obj.children[1:]
        return r

    def owriteParagraph(self, obj):
        if obj.children:
            imgAsOnlyChild = bool(len(obj.children) == 1 and isinstance(obj.getFirstChild(), advtree.ImageLink))
            # handle special case nothing but an image in a paragraph
            if imgAsOnlyChild and isinstance(obj.next, advtree.Paragraph): 
                img = obj.getFirstChild()
                img.moveto(obj.next.getFirstChild(), prefix=True)
                return SkipChildren()
            return ParagraphProxy(stylename=style.textbody)
        
    def owriteItem(self, item):
        li =text.ListItem()
        p = ParagraphProxy(stylename=style.textbody)
        li.addElement(p)
        li.writeto = p
        return li

    def owriteItemList(self, lst):
        if lst.numbered:
            return text.List(stylename=style.numberedlist)
        else:
            return text.List(stylename=style.unorderedlist)

    def owriteDefinitionList(self, obj):
        return text.List(stylename=style.definitionlist)

    def owriteDefinitionTerm(self, obj):
        li =text.ListItem()
        p = ParagraphProxy(stylename=style.definitionterm)
        li.addElement(p)
        li.writeto = p
        return li

    def owriteDefinitionDescription(self, obj):
        li = text.ListItem() 
        p = ParagraphProxy(stylename=style.indentedSingle)
        li.addElement(p)
        li.writeto = p
        return li


    def owriteBreakingReturn(self, obj):
        return text.LineBreak()

    def owriteCell(self, cell):
        t =  table.TableCell()
        p = ParagraphProxy(stylename=style.textbody)
        t.addElement(p)
        t.writeto = p
        # handle rowspan FIXME
        # 
        #rs = cell.rowspan
        #if rs:
        #    t.setAttribute(":numberrowsspanned",str(rs))
        return t    

    def owriteRow(self, row): # COLSPAN FIXME
        tr = table.TableRow()
        for c in row.children:
            cs =  c.colspan
            self.write(c,tr)
            if cs:
                tr.lastChild.setAttribute("numbercolumnsspanned",str(cs))
                for i in range(cs):
                    tr.addElement(table.CoveredTableCell())
        return SkipChildren(tr)

    def owriteCaption(self, obj):
        # are there caption not in tables ???? FIXME
        if isinstance(obj.parent, advtree.Table):
            return SkipChildren()
        pass # FIXME 

    def owriteTable(self, obj): # FIXME ADD FORMATTING
        # http://books.evc-cit.info/odbook/ch04.html#text-table-section
             
        t = table.Table()
        tc = table.TableColumn(stylename=style.dumbcolumn, 
                               numbercolumnsrepeated=str(obj.numcols)) # FIXME FIXME
        t.addElement(tc)
        
        captions = [c for c in obj.children if isinstance(c, advtree.Caption)]
        if not captions : # handle table w/o caption:
            return t
        else: # a section groups table-caption & table:
            if not len(captions) == 1:
                log("owriteTable: more than one Table Caption not handeled. Using only first Caption!")
            # group using a section
            sec = text.Section(stylename=style.sectTable, name="table section")
            p =  ParagraphProxy(stylename=style.tableCaption)
            sec.addElement(p)
            self.writeChildren(captions[0], p)# only one caption expected and allowed
            sec.addElement(t)
            sec.writeto=t
            return sec


# ---- inline formattings -------------------
# use span

    def owriteEmphasized(self, obj):
        return text.Span(stylename=style.emphasis)

    def owriteStrong(self, obj):
        return text.Span(stylename=style.strong)

    def owriteBold(self, obj):
        return text.Span(stylename=style.bold)

    def owriteItalic(self, obj):
        return text.Span(stylename=style.italic)

    def owriteSmall(self, obj): 
        return text.Span(stylename=style.small)

    def owriteBig(self, obj): 
        return text.Span(stylename=style.big)

    def owriteVar(self, obj): 
        return text.Span(stylename=style.var)

    def owriteDeleted(self, obj): 
        return text.Span(stylename=style.deleted)

    def owriteInserted(self, obj): 
        return text.Span(stylename=style.inserted)

    def owriteRuby(self, obj):
        return text.Ruby()

    def owriteRubyText(self, obj):
        return text.RubyText()

    def owriteRubyBase(self, obj):
        return text.RubyBase()

    def owriteRubyParentheses(self, obj):
        pass # FIXME

    def owriteSub(self, obj): 
        return text.Span(stylename=style.sub)

    def owriteSup(self, obj): 
        return text.Span(stylename=style.sup)

    def owriteSpan(self, obj): 
        return text.Span()

    def owriteOverline(self, s):
        return text.Span(stylename=style.overline)

    def owriteUnderline(self, s):
        return text.Span(stylename=style.underline)

    def owriteStrike(self, s):
        return text.Span(stylename=style.strike)



# ------- block formattings -------------------
# use paragraph

    def owriteCenter(self, s):
        return ParagraphProxy(stylename=style.center)

    def owriteCite(self, obj): 
        return text.Span(stylename=style.cite)

    def owriteDiv(self, obj): 
        return ParagraphProxy()
        
    def owriteTeletyped(self, obj):
        # (monospaced) or code, newlines ignored, spaces collapsed
        return text.Span(stylename=style.teletyped)


    def owritePreFormatted(self, n):
        # there seems to be no preformatted option in ODF
        # need to replace \n \t " "

        # FIXME TABS NOT RETURNED BY PARSER
        
        p = ParagraphProxy(stylename=style.preformatted) 
        rmap = {
            "\n":text.LineBreak,
            " ":text.S}
        col = []
        for c in n.getAllDisplayText().replace("\t", " "*4):
            if c in rmap:
                p.addText(u"".join(col))
                col = []
                p.addElement(rmap[c]())
            else:
                col.append(c)
        p.addText(u"".join(col)) # add remaining
        n.children = []  # remove the children
        return p


    def owriteCode(self, obj): 
        return text.Span(stylename=style.code)

    def owriteSource(self, obj): 
        return ParagraphProxy(stylename=style.source)

    
    def owriteBlockquote(self, s):
        "margin to the left & right"
        indentlevel = len(s.caption)-1
        return ParagraphProxy(stylename=style.blockquote)


    def owriteIndented(self, s):
        "Writes a indented Paragraph. Margin to the left.\n Need a lenght of Indented.caption of 1,2 or 3."
        indentStyles = (style.indentedSingle, style.indentedDouble, style.indentedTriple)  # 0, 1, 2
        indentLevel = min(len(s.caption)-1, len(indentStyles)-1) 
        return ParagraphProxy(stylename=indentStyles[indentLevel])
        
 
    def owriteMath(self, obj): 
        """
        get a MATHML from Latex
        translate element tree to odf.Elements
        """
        #log("math")
        r = writerbase.renderMath(obj.caption, output_mode='mathml', render_engine='blahtexml')        
        if not r:
            log("writerbase.renderMath failed!")
            return
        #print mathml.ET.tostring(r)
        
        def _withETElement(e, parent):
            # translate to odf.Elements
            for c in e.getchildren():
                n = math.Element(qname=(math.MATHNS, str(c.tag)))
                parent.addElement(n)
                if c.text:
                    text = c.text
                    #if not isinstance(text, unicode):  text = text.decode("utf8")
                    n.appendChild(odf.element.Text(text)) # n.addText(c.text)
                    # rffixme: odfpy0.8 errors:"AttributeError: Element instance has no attribute 'elements'" -> this is a lie!
                _withETElement(c, n)

        mathframe = draw.Frame(stylename=style.formula, zindex=0, anchortype="as-char") 
        mathobject = draw.Object() 
        mathframe.addElement(mathobject)
        mroot = math.Math()
        mathobject.addElement(mroot)
        _withETElement(r, mroot)
        return mathframe

    def owriteLink(self, obj): 
        a = text.A(href= obj.url or "#")
        if not obj.children:
            a.addText(obj.target)
        return a

    owriteArticleLink = owriteLink 
    obwriteLangLink = owriteLink 
    owriteNamespaceLink = owriteLink
    owriteInterwikiLink = owriteLink
    owriteSpecialLink = owriteLink



    def owriteURL(self, obj):
        a = text.A(href=obj.caption)
        if not obj.children:
            a.addText(obj.caption)
        return a


    def owriteNamedURL(self, obj):
        # FIXME handle references
        a = text.A(href=obj.caption)
        if not obj.children:
            name = "[%s]" % self.namedLinkCount
            self.namedLinkCount += 1
            a.addText(name)
        return a


    def owriteSpecialLink(self, obj): # whats that?
        a = text.A(href=obj.target)
        if not obj.children:
            a.addText(obj.target)
        return a

    def owriteCategoryLink(self, obj):
        if True: # FIXME, collect and add to the end of the page
            return SkipChildren()
        if not obj.colon and not obj.children:
            a = text.A(href=obj.target)
            a.addText(obj.target)
            return a

    def owriteLangLink(self, obj):
        return SkipChildren() # dont want them

    def owriteReference(self, t): 
        self.references.append(t)
        n =  text.Note(noteclass="footnote")
        nc = text.NoteCitation()
        n.addElement(nc )
        nc.addText(str(len(self.references)))
        nb = text.NoteBody()
        n.addElement( nb )
        p = ParagraphProxy(stylename="Footnote")
        nb.addElement(p)
        n.writeto = p
        return n

    def owriteReferenceList(self, t):
        # already in odf footnotes
        pass

    def owriteImageMap(self, obj):
        pass # write children # fixme
    
    def owriteImageLink(self,obj):
        # see http://books.evc-cit.info/odbook/ch04.html
        # see rl.writer for more advanced image integration, including inline, floating, etc.
        # http://code.pediapress.com/hg/mwlib.rl rlwriter.py

        from PIL import Image as PilImage        

        def sizeImage(w,h):
         
            """ calculate the target image size in inch. 
            @param: (w,h): w(idth), h(eight) of image in px
            @type int
            @return: (w,h): w(idth), h(eight) of target image in inch (!)
            @rtype float"""
            
            
            if obj.isInline:
                scale = 1 / self.conf.paper['IMG_DPI_STANDARD']
            else:
                scale = 1 / self.conf.paper['IMG_DPI_INLINE']
           
            wTarget = scale * w # wTarget is in inch now
            hTarget = scale * h # hTarget is in inch now
            
            ##2do: obey the value of thumpnail
            if wTarget > self.conf.paper['IMG_MAX_WIDTH'] or hTarget > self.conf.paper['IMG_MAX_HEIGHT']:
                # image still to large, re-resize to max possible:
                scale = min(self.conf.paper['IMG_MAX_WIDTH']/w, self.conf.paper['IMG_MAX_HEIGHT']/h)

                return (w*scale, h*scale)
            else:
                return (wTarget, hTarget)

        if obj.colon == True:
            return # writes children

        if not self.env or not self.env.images:
            return

        imgPath = self.env.images.getDiskPath(obj.target)#, size=targetWidth) ????
        if not imgPath:
            log.warning('invalid image url')
            return
        imgPath = imgPath.encode('utf-8')
               
        (wObj,hObj) = (obj.width or 0, obj.height or 0)
        # sometimes our parser delivers only one value, w or h, so set the other = 0

        try:
            img = PilImage.open(imgPath)
            if img.info.get('interlace',0) == 1:
                log.warning("got interlaced PNG which can't be handeled by PIL")
                return
        except IOError:
            log.warning('img can not be opened by PIL')
            return
        
        (wImg,hImg) = img.size
        
        if wImg == 0 or wImg == 0:
            return
        
        aspectRatio = wImg/hImg                           

        if wObj>0 and not hObj>0:
            hObj = wObj / aspectRatio
        elif hObj>0 and not wObj>0:
            wObj = aspectRatio / hObj
        elif wObj==0 and hObj==0: 
            wObj, hObj = wImg, hImg

        # sometimes the parser delivers only one value, w or h, so set the other "by hand"       
        (width, height) = sizeImage( wObj, hObj)
        
        widthIn = "%.2fin" % (width)# * scale)
        heightIn= "%.2fin" % (height)# * scale)
                
        innerframe = draw.Frame(stylename=style.frmInner, width=widthIn, height=heightIn)
        href = self.doc.addPicture(imgPath)
        innerframe.addElement(draw.Image(href=href))

        if obj.isInline():
            return SkipChildren(innerframe) # FIXME something else formatting?
        else:
            innerframe.addAttribute( "anchortype", "paragraph")


        widthIn = "%.2fin" % (width + style.frmOuter.internSpacing)# * scale)
        heightIn= "%.2fin" % (height)
        
        # set image alignment
        attrs = dict(width=widthIn, anchortype="paragraph")
        floats = dict(right  = style.frmOuterRight,
                      center = style.frmOuterCenter,
                      left   = style.frmOuterLeft)
        attrs["stylename"] = floats.get(obj.align, style.frmOuterLeft) 
        stylename=style.frmOuterLeft,
        frame = draw.Frame(**attrs)
        
        tb = draw.TextBox()
        frame.addElement(tb)
        p = ParagraphProxy(stylename=style.imgCaption)
        tb.addElement(p)
        p.addElement(innerframe)
        frame.writeto = p
        return frame


    def owriteNode(self, n):
        pass # simply write children

    def owriteGallery(self, obj):
        pass # simply write children FIXME

    def owriteHorizontalRule(self, obj):
        p = ParagraphProxy(stylename=style.hr)
        return p


# UNIMPLEMENTED  -----------------------------------------------

    def writeTimeline(self, obj): 
        data = obj.caption
        pass # FIXME

    def writeHiero(self, obj): # FIXME parser support
        data = obj.caption
        pass # FIXME
class OdtGenerator(DocumentGenerator):
    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 addText(self, data_box):
        text = data_box.getText()
        frame_style = Style(name="FrameStyle", family="graphic")
        debug("Angle: ", 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))

    def addImage(self, data_box):
        format = "PNG"
        image_file = tempfile.mkstemp(suffix="." + format)[1]
        data_box.image.save(image_file, format=format)
        x, y, width, height = data_box.getBoundsPrintSize(self.current_page_resolution)
        photo_frame = Frame(
            stylename=self.photo_style,
            x="%sin" % x,
            y="%sin" % y,
            width="%sin" % width,
            height="%sin" % height,
            anchortype="paragraph",
        )
        self.current_page.addElement(photo_frame)
        location = self.document.addPicture(image_file)
        photo_frame.addElement(Image(href=location))
        self.temp_images.append(image_file)

    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

    def addPage(self, page_data):
        self.current_page = self.newPage(page_data)
        self.current_page_resolution = page_data.resolution
        self.addBoxes(page_data.data_boxes)

    def save(self):
        name = self.name
        if not name.lower().endswith(".odt"):
            name += ".odt"
        self.document.save(name)
        for image in self.temp_images:
            try:
                os.unlink(image)
            except:
                debug("Error removing image: %s" % image)

    def __handlePageMaster(self, page_data):
        layout_name = "Page%s%s" % (page_data.width, page_data.height)
        if not layout_name in self.page_layouts:
            page_layout = PageLayout(name=layout_name)
            page_layout.addElement(
                PageLayoutProperties(
                    margintop="0in",
                    marginbottom="0in",
                    marginleft="0in",
                    marginright="0in",
                    pagewidth="%sin" % page_data.width,
                    pageheight="%sin" % page_data.height,
                )
            )
            self.document.automaticstyles.addElement(page_layout)
            self.page_layouts.append(layout_name)
        master_name = layout_name + "Master"
        if not master_name in self.page_masters:
            master_page = MasterPage(name=master_name, pagelayoutname=layout_name)
            self.document.masterstyles.addElement(master_page)
            self.page_masters.append(master_name)
        return master_name

    def __handleFrameStyle(self, text_data):
        style_name = "box%s%s%s%s%s" % (
            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.styles.addElement(frame_style)
            self.font_styles.append(style_name)
        return style_name

    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

    def convertFontStyle(self, style):
        if style == STYLE_OBLIQUE:
            return "oblique"
        elif style == STYLE_ITALIC:
            return "italic"
        return "normal"

    def convertFontWeight(self, weight):
        if weight == WEIGHT_BOLD:
            return "bold"
        return "normal"
Example #6
0
"""
    <text:h text:outline-level="1">An Image</text:h>
     <text:p>
       <draw:frame draw:name="graphics1" text:anchor-type="paragraph"
         svg:width="5in"
         svg:height="6.6665in" draw:z-index="0">
         <draw:image xlink:href="Pictures/campanile_fog.jpg" xlink:type="simple"
           xlink:show="embed"
           xlink:actuate="onLoad"/>
       </draw:frame>
     </text:p>
"""

textdoc.text.addElement(H(outlinelevel=1,text='An Image'))
p = P()
textdoc.text.addElement(p)
# add the image
# img_path is the local path of the image to include
img_path = r'..\data\img\metadator.png';
#img_path = 'D:\Document\PersonalInfoRemixBook\examples\ch17\campanile_fog.jpg'
href = textdoc.addPicture(img_path)
f = Frame(name="graphics1", anchortype="paragraph", width="5in", height="6.6665in",
zindex="0")
p.addElement(f)
img = Image(href=href, type="simple", show="embed", actuate="onLoad")
f.addElement(img)



# save the document
textdoc.save(fname)
Example #7
0
class OdtGenerator(DocumentGenerator):
    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 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))

    def addImage(self, data_box):
        format = 'PNG'
        image_file = tempfile.mkstemp(
            dir=ConfigurationManager.TEMPORARY_FOLDER, suffix='.' + format)[1]
        data_box.image.save(image_file, format=format)
        x, y, width, height = data_box.getBoundsPrintSize(
            self.current_page_resolution)
        photo_frame = Frame(stylename=self.photo_style,
                            x='%sin' % x,
                            y='%sin' % y,
                            width='%sin' % width,
                            height='%sin' % height,
                            anchortype='paragraph')
        self.current_page.addElement(photo_frame)
        location = self.document.addPicture(image_file)
        photo_frame.addElement(Image(href=location))
        self.temp_images.append(image_file)

    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

    def addPage(self, page_data):
        self.current_page = self.newPage(page_data)
        self.current_page_resolution = page_data.resolution
        self.addBoxes(page_data.data_boxes)

    def save(self):
        name = self.name
        if not name.lower().endswith('.odt'):
            name += '.odt'
        self.document.save(name)
        for image in self.temp_images:
            try:
                os.unlink(image)
            except:
                debug('Error removing image: %s', image)

    def __handlePageMaster(self, page_data):
        layout_name = 'Page%s%s' % (page_data.width, page_data.height)
        if not layout_name in self.page_layouts:
            page_layout = PageLayout(name=layout_name)
            page_layout.addElement(
                PageLayoutProperties(margintop='0in',
                                     marginbottom='0in',
                                     marginleft='0in',
                                     marginright='0in',
                                     pagewidth='%sin' % page_data.width,
                                     pageheight='%sin' % page_data.height))
            self.document.automaticstyles.addElement(page_layout)
            self.page_layouts.append(layout_name)
        master_name = layout_name + 'Master'
        if not master_name in self.page_masters:
            master_page = MasterPage(name=master_name,
                                     pagelayoutname=layout_name)
            self.document.masterstyles.addElement(master_page)
            self.page_masters.append(master_name)
        return master_name

    def __handleFrameStyle(self, text_data):
        style_name = 'box%s%s%s%s%s' % (
            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.styles.addElement(frame_style)
            self.font_styles.append(style_name)
        return style_name

    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

    def convertFontStyle(self, style):
        if style == Pango.Style.OBLIQUE:
            return 'oblique'
        elif style == Pango.Style.ITALIC:
            return 'italic'
        return 'normal'

    def convertFontWeight(self, weight):
        if weight == Pango.Weight.BOLD:
            return 'bold'
        return 'normal'
Example #8
0
class textdoc:

    def __init__(self):
        self.textdoc = OpenDocumentText()
        
        self.oneandhalflines = Style(name="oneandhalflines", parentstylename="Standard", family="paragraph")
        self.oneandhalflines.addElement(ParagraphProperties(lineheight="1.5"))
        self.textdoc.automaticstyles.addElement(self.oneandhalflines)
        
        # Create a style for the paragraph with page-break
        self.withbreak = Style(name="WithBreak", parentstylename="Standard", family="paragraph")
        self.withbreak.addElement(ParagraphProperties(breakbefore="page"))
        self.textdoc.automaticstyles.addElement(self.withbreak)

        self.footercenterstyle = Style(name="footercenter", family="paragraph", parentstylename="Standard")
        self.footercenterstyle.addElement(ParagraphProperties(textalign="center"))
        self.textdoc.automaticstyles.addElement(self.footercenterstyle)

        self.footerstyle = FooterStyle()
        self.footerstyle.addElement(HeaderFooterProperties(padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="none",shadow="none", minheight="1cm"))

        #Text Header
        self.plheaderstyle = PageLayout(name="pl")
        self.plheaderstyle.addElement(PageLayoutProperties(marginleft="2cm",marginright="2cm",margintop="1cm",marginbottom="1cm"))
        self.headerstyle = HeaderStyle()
        self.headerstyle.addElement(HeaderFooterProperties(backgroundcolor="#e6e6ff",padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="2.01pt solid #000099",shadow="none", minheight="1cm"))
        self.plheaderstyle.addElement(self.headerstyle)
        self.plheaderstyle.addElement(self.footerstyle)
        self.textdoc.automaticstyles.addElement(self.plheaderstyle)
        
        #image header
        self.pliheaderstyle = PageLayout(name="pli")
        self.pliheaderstyle.addElement(PageLayoutProperties(marginleft="2cm",marginright="2cm",margintop="1cm",marginbottom="1cm"))
        self.headeristyle = HeaderStyle()
        self.headeristyle.addElement(HeaderFooterProperties(padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="none",shadow="none", minheight="2cm"))
        self.pliheaderstyle.addElement(self.headeristyle)
        self.pliheaderstyle.addElement(self.footerstyle)   
        self.textdoc.automaticstyles.addElement(self.pliheaderstyle)
        
        self.h1style = Style(name="Heading 1",  family="paragraph",parentstylename="Heading 1")
        self.h1style.addElement(GraphicProperties(fill="solid",fillcolor="#e6e6ff"))
        self.h1style.addElement(TextProperties(attributes={'fontsize':"14pt",'fontweight':"bold",'color':"#000099" }))
        self.h1style.addElement(ParagraphProperties(breakbefore="page",margintop="0.4cm",marginbottom="0.2cm",backgroundcolor="#e6e6ff",padding="0.05cm",borderleft="none",borderright="none",bordertop="none",borderbottom="2.01pt solid #000099",shadow="none"))
        self.textdoc.automaticstyles.addElement(self.h1style)

        self.h2style = Style(name="Heading 2s", family="paragraph",parentstylename="Heading 2")
        self.h2style.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" }))
        self.h2style.addElement(ParagraphProperties(marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false"))
        self.textdoc.automaticstyles.addElement(self.h2style)
        
        self.h2bstyle = Style(name="Heading 2b", family="paragraph",parentstylename="Heading 2")
        self.h2bstyle.addElement(ParagraphProperties(breakbefore="page",marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false"))
        self.textdoc.automaticstyles.addElement(self.h2bstyle)

        self.h3style = Style(name="Heading 3s", family="paragraph",parentstylename="Heading 3")
        self.h3style.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" }))
        self.h3style.addElement(ParagraphProperties(marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false"))
        self.textdoc.automaticstyles.addElement(self.h3style)
        self.h3bstyle = Style(name="Heading 3b", family="paragraph",parentstylename="Heading 3")
        self.h3bstyle.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold",'color':"#000099" }))
        self.h3bstyle.addElement(ParagraphProperties(breakbefore="page",marginleft="0cm",marginright="0cm",margintop="0.2cm",marginbottom="0.2cm",lineheight="150%",textindent="1.2cm",autotextindent="false"))
        self.textdoc.automaticstyles.addElement(self.h3bstyle)

        self.TAB_style = Style(name="Table", family="table-cell", parentstylename="Standard")
        self.TAB_style.addElement(TableCellProperties(border="0.05pt solid #000000"))
        self.textdoc.automaticstyles.addElement(self.TAB_style)

        self.TAB_stylered = Style(name="Table red", family="table-cell", parentstylename="Standard")
        self.TAB_stylered.addElement(TableCellProperties(backgroundcolor="ff0000",border="0.05pt solid #000000"))
        self.textdoc.automaticstyles.addElement(self.TAB_stylered)

        self.tableheaders = Style(name="Table Headers", family="paragraph", parentstylename="Standard")
        self.tableheaders.addElement(ParagraphProperties(numberlines="false", linenumber="0",textalign="center",margintop="0.2cm",marginbottom="0.2cm"))
        self.tableheaders.addElement(TextProperties(attributes={'fontsize':"12pt",'fontweight':"bold"}))
        self.textdoc.styles.addElement(self.tableheaders)

        self.tablecontents = Style(name="Table Contents", family="paragraph", parentstylename="Standard")
        self.tablecontents.addElement(ParagraphProperties(numberlines="false", linenumber="0",margintop="0.2cm",marginbottom="0.2cm"))
        self.tablecontents.addElement(TextProperties(attributes={'fontsize':"12pt" }))
        self.textdoc.styles.addElement(self.tablecontents)

        self.tablecontentscenter = Style(name="Table Contents Center", family="paragraph", parentstylename="Standard")
        self.tablecontentscenter.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="center",margintop="0.2cm",marginbottom="0.2cm"))
        self.tablecontentscenter.addElement(TextProperties(attributes={'fontsize':"12pt" }))
        self.textdoc.styles.addElement(self.tablecontentscenter)

        self.tablecontentscenterred = Style(name="Table Contents Center Red", family="paragraph", parentstylename="Standard")
        self.tablecontentscenterred.addElement(ParagraphProperties(numberlines="false", linenumber="0", textalign="center", backgroundcolor="#ff0000",margintop="0.2cm",marginbottom="0.2cm"))
        self.tablecontentscenterred.addElement(TextProperties(attributes={'fontsize':"12pt" }))
        self.textdoc.styles.addElement(self.tablecontentscenterred)
        
    def addTitle(self,text):
        title = H(stylename=self.h1style,text=text,outlinelevel=1)
        self.textdoc.text.addElement(title)
    
    def addTitle2(self,text,newpage=False):
        if newpage:
            title = H(stylename=self.h2bstyle,text=text,outlinelevel=2)
        else:
            title = H(stylename=self.h2style,text=text,outlinelevel=2)
        self.textdoc.text.addElement(title)
        
    def addTitle3(self,text,newpage=False):
        if newpage:
            title = H(stylename=self.h3bstyle,text=text,outlinelevel=3)
        else:
            title = H(stylename=self.h3style,text=text,outlinelevel=3)
        self.textdoc.text.addElement(title)
        
    def addParagraph(self,text):
        #paragraph = P(stylename=self.oneandhalflines,text=text)
        paragraph = P(text=text)
        self.textdoc.text.addElement(paragraph) 
        
    def addBlankLine(self):
        self.addParagraph("")
        
    def addImage(self,image_path,name):
        if not name:
            name = image_path
        p = P()
        self.textdoc.text.addElement(p)
        href = self.textdoc.addPicture(image_path)
        f = Frame(name=name, anchortype="paragraph", width="17cm", height="7.5cm", zindex="0")
        p.addElement(f)
        img = Image(href=href, type="simple", show="embed", actuate="onLoad")
        f.addElement(img)
        
    def addNewPage(self):
        breakpage = P(stylename=self.withbreak,text="")
        self.textdoc.text.addElement(breakpage)
        
    def addList(self,elements):
        textList = List(stylename="L1")
        for element in elements:
         item = ListItem()
         item.addElement(P(text=element))
         textList.addElement(item)
        self.textdoc.text.addElement(textList)
        
    def addTable(self,tabledata,headers,formater=None):
        if formater and len(formater)!=len(tabledata):
            raise ValueError
        if formater is None:
            formater = [[""]*len(tabledata[0])]*len(tabledata)
        table = Table()
        columns = len(headers)
        table.addElement(TableColumn(numbercolumnsrepeated=columns))
        tr = TableRow()
        table.addElement(tr)
        for header in headers:
            tc = TableCell(stylename="Table")
            tr.addElement(tc)
            p = P(stylename=self.tableheaders,text=header)
            tc.addElement(p)
        for line,formats in zip(tabledata,formater):
            tr = TableRow()
            table.addElement(tr)
            for column,cformat in zip(line,formats):
                if cformat == "centerred":
                    cellformat = self.tablecontentscenter
                elif cformat == "center":
                    cellformat = self.tablecontentscenterred
                else:
                    cellformat = self.tablecontents
                tc = TableCell(stylename="Table")
                tr.addElement(tc)
                p = P(stylename=cellformat,text=column)
                tc.addElement(p)
        self.textdoc.text.addElement(table)

    def addHeaderFooter(self,header=None,footer=None):
        if header or footer:
            mp = MasterPage(name="Standard", pagelayoutname=self.plheaderstyle)
            self.textdoc.masterstyles.addElement(mp)
            if header:
                h = Header()
                hp = P(text=header)#,stylename=self.headerstyle)
                h.addElement(hp)
                mp.addElement(h)
            if footer:
                f = Footer()
                fp = P(text=footer,stylename=self.footercenterstyle)
                f.addElement(fp)
                mp.addElement(f)
        
    def addImageHeaderFooter(self,header=None,footer=None):
        if header or footer:
            mp = MasterPage(name="Standard", pagelayoutname=self.pliheaderstyle)
            self.textdoc.masterstyles.addElement(mp)
            if header:
                h = Header()
                p = P()
                href = self.textdoc.addPicture(header)
                f = Frame(name="membrete", anchortype="paragraph", width="17cm", height="1.5cm", zindex="0")
                p.addElement(f)
                img = Image(href=href, type="simple", show="embed", actuate="onLoad")
                f.addElement(img)
                h.addElement(p)
                
                mp.addElement(h)
            if footer:
                fo = Footer()
                pn = PageNumber()
                fp = P(text=footer,stylename=self.footercenterstyle)#FIXME: Pagen number shoulb be better
                fp.addElement(pn)
                fo.addElement(fp)
                mp.addElement(fo)
        
        
    def save(self,filename):
        self.textdoc.save(filename)