Пример #1
0
    def image(self, src, title, alt_text):
        # embed picture - TODO: optionally just link it
        media_type = guess_type(src)
        fragment_ext = urlparse.urlparse(src)[2].split('.')[-1]
        self.image_entry_id = hasher()
        fragment_name = 'Pictures/%s.%s' % (self.image_entry_id, fragment_ext)
        imagedata = urlopen(src).read()
        try:
            if not fragment_ext.endswith('svg'):
                # delay our PIL dependency until really needed
                from PIL import Image
                import cStringIO

                imagefile = cStringIO.StringIO(imagedata)

                # obtain image aspect ratio
                image_w, image_h = Image.open(imagefile).size
            else:
                # PIL does not really support svg, so let's try heuristics
                # & find the aspect ratio ourselves
                from BeautifulSoup import BeautifulSoup

                imagefile = BeautifulSoup(imagedata)
                image_w = float(imagefile.svg['width'])
                image_h = float(imagefile.svg['height'])
        except:
            # unable to extract aspect ratio
            image_w, image_h = (100, 100)

        image_ratio = image_w / float(image_h)

        frame_x, frame_y = (2, 4)
        frame_w, frame_h = (22, 12)
        frame_ratio = frame_w / float(frame_h)

        if image_ratio > frame_ratio:
            image_w = frame_w
            image_h = int(frame_w / image_ratio)
            frame_y += (frame_h - image_h) / 2
        else:
            image_w = int(frame_h * image_ratio)
            image_h = frame_h
            frame_x += (frame_w - image_w) / 2

        args = {
            'style': u'md2odp-ImageStyle',
            'size': (u'%dcm' % image_w, u'%dcm' % image_h),
            'position': (u'%dcm' % frame_x, u'%dcm' % frame_y),
            'presentation_class': u'graphic'
        }
        if title is not None:
            args['text'] = unicode(title)
        frame = odf_create_image_frame(fragment_name, **args)

        if alt_text is not None:
            frame.set_svg_description(unicode(alt_text))

        self.doc_manifest.add_full_path(fragment_name, media_type[0])
        self.document.set_part(fragment_name, imagedata)
        return ODFPartialTree.from_metrics_provider([frame], self)
Пример #2
0
 def test_create_image_frame(self):
     frame = odf_create_image_frame('Pictures/zoe.jpg')
     expected = ('<draw:frame svg:width="1cm" svg:height="1cm" '
                   'text:anchor-type="paragraph">'
                   '<draw:image xlink:href="Pictures/zoe.jpg"/>'
                 '</draw:frame>')
     self.assertEqual(frame.serialize(), expected)
Пример #3
0
 def test_create_image_frame(self):
     frame = odf_create_image_frame('Pictures/zoe.jpg')
     expected = ('<draw:frame svg:width="1cm" svg:height="1cm" '
                   'draw:z-index="0">'
                   '<draw:image xlink:href="Pictures/zoe.jpg" '
                     'xlink:type="simple" xlink:show="embed" '
                     'xlink:actuate="onLoad"/>'
                 '</draw:frame>')
     self.assertEqual(frame.serialize(), expected)
Пример #4
0
 def test_create_image_frame(self):
     frame = odf_create_image_frame('Pictures/zoe.jpg')
     expected = ('<draw:frame svg:width="1cm" svg:height="1cm" '
                   'draw:z-index="0">'
                   '<draw:image xlink:href="Pictures/zoe.jpg" '
                     'xlink:type="simple" xlink:show="embed" '
                     'xlink:actuate="onLoad"/>'
                 '</draw:frame>')
     self.assertEqual(frame.serialize(), expected)
Пример #5
0
 def GET(self, resource, context):
     if lpod_is_install is False:
         msg = ERROR(u'Please install LPOD')
         return context.come_back(msg)
     document = odf_new_document_from_type('text')
     body = document.get_body()
     root = context.root
     table = odf_create_table(u"Table 1",
                              width=5,
                              height=1,
                              style='table-cell')
     for brain in root.search(format='product').get_documents():
         # Get product
         product = root.get_resource(brain.abspath)
         cover = product.get_resource(product.get_property('cover'))
         # Add line
         row = odf_create_row(width=5)
         cell = odf_create_cell(u"")
         file = context.database.fs.open(cover.handler.key)
         local_uri = document.add_file(file)
         image_frame = odf_create_image_frame(local_uri,
                                              size=('5cm', '5cm'),
                                              position=('0cm', '0cm'),
                                              anchor_type='as-char')
         paragraph = cell.get_element('text:p')
         paragraph.append(image_frame)
         cell.append(paragraph)
         row.set_cell(0, cell)
         row.set_cell_value(1, brain.reference)
         row.set_cell_value(2, brain.title)
         row.set_cell_value(3, u'%s' % product.get_price_without_tax())
         table.append_row(row)
         # Get declinations
         for d in product.search_resources(cls=Declination):
             price = d.parent.get_price_without_tax(id_declination=d.name,
                                                    pretty=True)
             row = odf_create_row(width=5)
             row.set_cell_value(1, 'reference')
             row.set_cell_value(2, d.get_declination_title())
             row.set_cell_value(3, u'%s' % price)
             row.set_cell_value(4, d.get_property('stock-quantity'))
             table.append(row)
     body.append(table)
     f = StringIO()
     document.save(f)
     content = f.getvalue()
     f.close()
     context.set_content_type('application/vnd.oasis.opendocument.text')
     context.set_content_disposition('attachment', 'export.odt')
     return content
Пример #6
0
 def GET(self, resource, context):
     if lpod_is_install is False:
         msg = ERROR(u'Please install LPOD')
         return context.come_back(msg)
     document = odf_new_document_from_type('text')
     body = document.get_body()
     root = context.root
     table = odf_create_table(u"Table 1", width=5, height=1, style='table-cell')
     for brain in root.search(format='product').get_documents():
         # Get product
         product = root.get_resource(brain.abspath)
         cover = product.get_resource(product.get_property('cover'))
         # Add line
         row = odf_create_row(width=5)
         cell = odf_create_cell(u"")
         file = context.database.fs.open(cover.handler.key)
         local_uri = document.add_file(file)
         image_frame = odf_create_image_frame(local_uri, size=('5cm', '5cm'),
             position=('0cm', '0cm'), anchor_type='as-char')
         paragraph = cell.get_element('text:p')
         paragraph.append(image_frame)
         cell.append(paragraph)
         row.set_cell(0, cell)
         row.set_cell_value(1, brain.reference)
         row.set_cell_value(2, brain.title)
         row.set_cell_value(3, u'%s' % product.get_price_without_tax())
         table.append_row(row)
         # Get declinations
         for d in product.search_resources(cls=Declination):
             price = d.parent.get_price_without_tax(id_declination=d.name, pretty=True)
             row = odf_create_row(width=5)
             row.set_cell_value(1, 'reference')
             row.set_cell_value(2, d.get_declination_title())
             row.set_cell_value(3, u'%s' % price)
             row.set_cell_value(4, d.get_property('stock-quantity'))
             table.append(row)
     body.append(table)
     f = StringIO()
     document.save(f)
     content = f.getvalue()
     f.close()
     context.set_content_type('application/vnd.oasis.opendocument.text')
     context.set_content_disposition('attachment', 'export.odt')
     return content
Пример #7
0
page1.set_transition("fade", "fadeOverColor")

#
# Image Frame
#

# Start a new page
page2 = odf_create_draw_page(u"page2")
body.append(page2)

# Embed an image from a file name
local_uri = document.add_file(u'images/zoé.jpg')

# Add image frame
image_frame = odf_create_image_frame(local_uri,
                                     size=('60mm', '45mm'),
                                     position=('4.5cm', '7cm'))
page2.append(image_frame)

# Some text side by side
list = odf_create_list([u"Item 1", u"Item 2", u"Item 3"])
text_frame = odf_create_text_frame(list,
                                   size=('7cm', '2.5cm'),
                                   position=('12.5cm', '7cm'),
                                   style=u"colored")
page2.append(text_frame)

# Add a transition for this frame
page2.set_transition("fade", "fadeOverColor")

#
Пример #8
0
    def fillDANFE(self):
        body = self.danfe.get_body()
        danfe = body.get_table_list()[0]
        danfe_value = None

        for n in self.xml_tree.iter():
            #print n
            if n.tag.find(self._namespace) == -1:
                continue

            try:
                danfe_key = u'.'.join([
                    n.getparent().tag.replace('{'+self._namespace+'}', ''),
                    n.tag.replace('{'+self._namespace+'}', '')]
                )

                if re.search('[.][vqp][A-Z]', danfe_key):
                    try:
                        danfe_value = decimal.Decimal(n.text)
                    except decimal.InvalidOperation:
                        danfe_value = None
                    #print danfe_key, danfe_value
                elif re.search('[.][d][A-Z]', danfe_key):
                    try:
                        danfe_value = datetime.datetime.strptime(n.text, '%Y-%m-%d')
                    except:
                        raise
                elif danfe_key.find('nNF') != -1:
                    danfe_value = int(n.text)
                elif danfe_key.find('CEP') != -1:
                    danfe_value = n.text[:5] + '-' + n.text[5:]
                elif danfe_key.find('CNPJ') != -1:
                    danfe_value = n.text[:2] + '.' +\
                                  n.text[2:5] + '.' +\
                                  n.text[5:8] + '/' +\
                                  n.text[8:12] + '-' + n.text[12:]

                elif danfe_key.find('CPF') != -1:
                    danfe_value = n.text[:3] + '.' +\
                                  n.text[3:6] + '.' +\
                                  n.text[6:9] + '-' +\
                                  n.text[9:]

                elif danfe_key.find('chNFe') != -1:
                    danfe_value = n.text[:4] + '.' +\
                                  n.text[4:8] + '.' +\
                                  n.text[8:12] + '.' +\
                                  n.text[12:16] + '.' +\
                                  n.text[16:20] + '.' +\
                                  n.text[20:24] + '.' +\
                                  n.text[24:28] + '.' +\
                                  n.text[28:32] + '.' +\
                                  n.text[32:36] + '.' +\
                                  n.text[36:40] + '.' +\
                                  n.text[40:]
                elif danfe_key.find('modFrete') != -1:
                    if n.text == '0':
                        danfe_value = "0 - EMITENTE"
                    elif n.text == '1':
                        danfe_value = "1 - DESTINATARIO"
                elif danfe_key.find('dhRecbto') != -1:
                    danfe_value = n.text[8:10] + '/' + n.text[5:7] + '/' + n.text[:4] + ' ' + n.text[11:]
                else:
                    danfe_value = n.text
                #print danfe_key
            except AttributeError:
                danfe_key = None

            if danfe_key:
                if re.search('ICMS[0-9][0-9]\.', danfe_key):
                    danfe_key = danfe_key[:4] + danfe_key[6:]
                    #print danfe_key

                if danfe_key == u'emit.xNome':
                    xnome = danfe_value

                for x, y, c in danfe.get_cells(content=u'%%'+danfe_key+u'%%'):
                    #print c.get_type(), c.get_value()
                    if isinstance(danfe_value, str) or isinstance(danfe_value, unicode):
                        c.set_value(c.get_value().replace(u'%%'+danfe_key+u'%%', danfe_value))
                    else:
                        c.set_value(danfe_value)

                    danfe.set_cell((x, y), c)
                    if danfe_key.find('ide.nNF') == -1 and danfe_key.find('ide.serie') == -1:
                        break

        # Put the logo
        x, y, c = danfe.get_cells(content=u'danfe.xLogo')[0]
        logo_uri = self.danfe.add_file(self.logo)

        frame = odf_create_image_frame(
            logo_uri,
            size=('5.20cm', '2.10cm'),
            position=('0cm', '0cm')
        )


        #frame.set_size(frame.get_size())
        #frame.set_attribute('table:end-cell-address', 'Paisagem.F8')
        #print frame.get_attributes()

        danfe.set_cell_image((x, y), frame, type=self.danfe.get_type())
        #frame.set_size(('5.87cm', '2.65cm'))
        danfe.get_frame_list()[0].set_attribute('table:end-cell-address', 'Paisagem.F8')
        danfe.get_frame_list()[0].set_attribute('table:end-x', '5.20cm')
        danfe.get_frame_list()[0].set_attribute('table:end-y', '2.10cm')
        danfe.get_frame_list()[0].set_attribute('svg:width', '5.20cm')
        danfe.get_frame_list()[0].set_attribute('svg:height', '2.10cm')
        #print danfe.get_frame_list()[0].get_attributes()

        # Put the barcode
        x, y, c = danfe.get_cells(content=u'danfe.xBarcode')[0]
        self.genBarcode()

        barcode_uri = self.danfe.add_file(self.nfe_id + '.png')

        frame = odf_create_image_frame(
            barcode_uri,
            size=('9.35cm', '0.85cm'),
            position=('0cm', '0cm')
        )

        danfe.set_cell_image((x, y), frame, type=self.danfe.get_type())
        danfe.get_frame_list()[1].set_attribute('table:end-cell-address', 'Paisagem.Z3')

        # Put the canhoto
        x, y, c = danfe.get_cells(content=u'danfe.xCanhoto')[0]
        danfe_value = u'RECEBEMOS DE %s O(S) PRODUTO(S) CONSTANTE(S) DA NOTA FISCAL INDICADA AO LADO' % xnome
        c.set_value(danfe_value)

        danfe.set_cell((x, y), c)

        # Clean the unused fields
        for x, y, c in danfe.get_cells(content=u'%%'):
            value = c.get_value() or '%%None%%'
            regex = re.search('%%.*%%', value)
            c.set_value(value.replace(regex.group(0), u''))
            danfe.set_cell((x, y), c)


        self.danfe.save()
        os.unlink(self.nfe_id + '.png')
Пример #9
0
    # Presentation got a body in which content is stored
    presentation_body = presentation.get_body()

    # For each image, we create a page in the presentation and display the image
    # and some text on this frame
    for image in images_pool:
        # add the file to the document
        uri = presentation.add_file(image.path)

        # Create an underlying page for the image and the text
        page = odf_create_draw_page("Page "+ image.name)

        # Create a frame for the image
        image_frame = odf_create_image_frame(
            url = uri,
            name = image.name,
            text = "",                            # Text over the image object
            size = (image.disp_w, image.disp_h),  # Display size of image
            anchor_type = 'page',
            page_number = None,
            position = (image.pos_x, image.pos_y),
            style = None
            )

        # Append all the component
        page.append(image_frame)
        presentation_body.append(page)

    # Finally save the result
    presentation.save(target = output_file, pretty = True)
Пример #10
0
    ratio = embedded_image_ratio(uri, part)
    max_border = 16.0  # max size of the greatest border, in cm
    a = max_border * ratio
    b = max_border
    if ratio > 1.0:
        a /= ratio
        b /= ratio

    # Create an underlying page for the image and the text
    page = odf_create_draw_page("page " + name)

    # Create a frame for the image
    image_frame = odf_create_image_frame(
        url=uri,
        text="",  # Text over the image object
        size=("%scm" % a, "%scm" % b),  # Display size of image
        anchor_type='page',
        page_number=None,
        position=('3.5cm', '3.5 cm'),
        style=None)

    # Add some text object somehere on the frame, with a text frame
    legend = "Image %s from Wikipedia document / %s" % (name, filename)
    text_frame = odf_create_text_frame(legend,
                                       size=('26cm', '2cm'),
                                       position=('0.5cm', '0.5cm'),
                                       style=u"Standard",
                                       text_style=u"Standard")

    # Append all the component, do not forget to add the actuel image file
    # into the Picture global directory of the presentation file with set_part
    page.append(text_frame)
Пример #11
0
    file_name = source[0]

    presentation = odf_get_document(file_name)
    presentation_body = presentation.get_body()

    uri = presentation.add_file(options.image)

    width, height = make_image_size(options.image, float(options.size))

    # Create a frame for the image
    image_frame = odf_create_image_frame(
            url = uri,
            name = file_name,
            text = "",                # Text over the image object
            size = (width, height),   # Display size of image
            anchor_type = 'page',
            page_number = None,
            position = (pos_x, pos_y),
            style = None
            )
    image_frame.set_svg_title(title)
    image_frame.set_svg_description(text)

    # Append all the component
    i = start
    while True:
        slide = presentation_body.get_draw_page(position = i)
        # Create a frame for the image
        image_frame = odf_create_image_frame(
            url = uri,
            name = file_name,
Пример #12
0
    def image(self, src, title, alt_text):
        # embed picture - TODO: optionally just link it
        media_type = guess_type(src)
        fragment_ext = urlparse.urlparse(src)[2].split('.')[-1]
        self.image_entry_id = hasher()
        fragment_name = 'Pictures/%s.%s' % (self.image_entry_id,
                                            fragment_ext)
        imagedata = urlopen(src).read()
        try:
            if not fragment_ext.endswith('svg'):
                # delay our PIL dependency until really needed
                from PIL import Image
                import cStringIO

                imagefile = cStringIO.StringIO(imagedata)

                # obtain image aspect ratio
                image_w, image_h = Image.open(imagefile).size
            else:
                # PIL does not really support svg, so let's try heuristics
                # & find the aspect ratio ourselves
                from BeautifulSoup import BeautifulSoup

                imagefile = BeautifulSoup(imagedata)
                image_w = float(imagefile.svg['width'])
                image_h = float(imagefile.svg['height'])
        except:
            # unable to extract aspect ratio
            image_w, image_h = (100, 100)

        image_ratio = image_w / float(image_h)

        frame_x, frame_y = (2, 4)
        frame_w, frame_h = (22, 12)
        frame_ratio = frame_w / float(frame_h)

        if image_ratio > frame_ratio:
            image_w = frame_w
            image_h = int(frame_w / image_ratio)
            frame_y += (frame_h - image_h) / 2
        else:
            image_w = int(frame_h * image_ratio)
            image_h = frame_h
            frame_x += (frame_w - image_w) / 2

        args = {'style': u'md2odp-ImageStyle',
                'size': (u'%dcm' % image_w, u'%dcm' % image_h),
                'position': (u'%dcm' % frame_x, u'%dcm' % frame_y),
                'presentation_class': u'graphic'}
        if title is not None:
            args['text'] = unicode(title)
        frame = odf_create_image_frame(fragment_name, **args)

        if alt_text is not None:
            frame.set_svg_description(unicode(alt_text))

        self.doc_manifest.add_full_path(fragment_name,
                                        media_type[0])
        self.document.set_part(fragment_name,
                               imagedata)
        return ODFPartialTree.from_metrics_provider([frame], self)
Пример #13
0
        image_style = odf_create_style('graphic', parent="Graphics")
        image_style.set_style_properties({'style:horizontal-pos': u"center",
            'style:horizontal-rel': u"paragraph"})
        context['doc'].insert_style(image_style, automatic=True)
        styles['image_style'] = image_style

    # In text application, image must be inserted in a paragraph
    if context["top"].get_tagname() == "office:text":
        container = odf_create_paragraph()
        context["top"].append_element(container)
    else:
        container = context["top"]

    if caption:
        paragraph = odf_create_paragraph()
        image_frame = odf_create_image_frame(local_uri, size=size,
                style=image_style.get_style_name())
        paragraph.append_element(image_frame)
        paragraph.append_element(caption)
        # A new frame, we fix only the width
        text_frame = odf_create_text_frame(paragraph, size=(size[0], None),
                style=caption_style.get_style_name())
        container.append_element(text_frame)
    else:
        image_frame = odf_create_image_frame(local_uri, size=size,
                style=image_style.get_style_name())
        container.append_element(image_frame)



def convert_image(node, context):
    image = node.get("uri")
Пример #14
0
    # Cells are XML elements
    second_cell.clear()
    second_cell.append(odf_create_paragraph(u"World"))

    # Modified cells must be pushed back
    # Could be pushed to another position
    table.set_cell((1, 0), second_cell)

    # Append a column (and adjust the table size)
    table.append_column(odf_create_column())

    # Add an image in the document
    image_uri = document.add_file('../.static/banner-lpod_en.png')

    # Images are in frame
    frame = odf_create_image_frame(image_uri, size=('11.87cm', '1.75cm'),
            position=('0cm', '0cm'))

    # Displaying an image in a cell is tricky: the document type must be
    # given or the table attached to the document
    table.set_cell_image((-1, 0), frame, type=document.get_type())

    # The table is a regular element
    body.append(table)

# Save
filename = 'spreadsheet.ods'
document.save(filename, pretty=True)
print 'Document "%s" generated.' % filename
    max_border = 16.0   # max size of the greatest border, in cm
    a = max_border * ratio
    b = max_border
    if ratio > 1.0:
        a /= ratio
        b /= ratio

    # Create an underlying page for the image and the text
    page = odf_create_draw_page("page "+name)

    # Create a frame for the image
    image_frame = odf_create_image_frame(
        url = uri,
        text = "",                          # Text over the image object
        size = ("%scm" % a, "%scm" % b),    # Display size of image
        anchor_type = 'page',
        page_number = None,
        position = ('3.5cm','3.5 cm'),
        style = None
        )

    # Add some text object somehere on the frame, with a text frame
    legend = "Image %s from Wikipedia document / %s" % (name, filename)
    text_frame = odf_create_text_frame(
        legend,
        size = ('26cm', '2cm'),
        position = ('0.5cm', '0.5cm'),
        style = u"Standard",
        text_style = u"Standard")

    # Append all the component, do not forget to add the actuel image file
Пример #16
0
# Add a transition for this page
page1.set_transition("fade", "fadeOverColor")

#
# Image Frame
#

# Start a new page
page2 = odf_create_draw_page(u"page2")
body.append(page2)

# Embed an image from a file name
local_uri = document.add_file(u'images/zoé.jpg')

# Add image frame
image_frame = odf_create_image_frame(local_uri, size=('60mm', '45mm'),
                                     position=('4.5cm', '7cm'))
page2.append(image_frame)

# Some text side by side
list = odf_create_list([u"Item 1", u"Item 2", u"Item 3"])
text_frame = odf_create_text_frame(list, size=('7cm', '2.5cm'),
                                   position=('12.5cm', '7cm'),
                                   style=u"colored")
page2.append(text_frame)

# Add a transition for this frame
page2.set_transition("fade", "fadeOverColor")

#
# Shapes
#