def init_doc(mimetype):
    # Text mode
    if mimetype == "application/vnd.oasis.opendocument.text":
        output_doc = odf_new_document_from_type("text")

        # Begin with a TOC
        output_body = output_doc.get_body()
        output_body.append_element(odf_create_toc())
    # Spreadsheet mode
    elif mimetype in ("application/vnd.oasis.opendocument.spreadsheet",
                      "text/csv"):
        output_doc = odf_new_document_from_type("spreadsheet")
    # Presentation mode
    else:
        output_doc = odf_new_document_from_type("presentation")

    return output_doc
Exemple #2
0
 def action_export_as_ods(self, resource, context, form):
     if lpod_is_install is False:
         msg = ERROR(u'Please install LPOD')
         return context.come_back(msg)
     # XXX Create a new process and send ODS file by mail for performances ?
     # XXX We do not export product without declination
     # XXX We do not export product without product model
     # Get list of groups
     groups = []
     for option in UserGroup_Enumerate.get_options():
         group = context.root.get_resource(option['name'])
         if group.get_property('use_default_price') is True:
             continue
         groups.append(group)
     # DB
     root = context.root
     shop = get_shop(resource)
     document = odf_new_document_from_type('spreadsheet')
     body = document.get_body()
     models = shop.get_resource('products-models').get_resources()
     for product_model in models:
         lines = []
         # We create one TAB by product model
         table = odf_create_table(product_model.get_title())
         search = root.search(product_model=str(product_model.get_abspath()))
         for brain in search.get_documents():
               product = root.get_resource(brain.abspath)
               for d in product.search_resources(cls=Declination):
                   # Ref - Declination name - Declination title
                   line = [product.get_property('reference'),
                           d.name,
                           d.get_declination_title().encode('utf-8')]
                   # Stock
                   line.append(str(d.get_quantity_in_stock()))
                   # Price by group (HT or TTC)
                   for group in groups:
                       k_price = {'id_declination': d.name,
                                  'prefix': group.get_prefix(),
                                  'pretty': True}
                       if group.get_property('show_ht_price'):
                           price = product.get_price_without_tax(**k_price)
                       else:
                           price = product.get_price_with_tax(**k_price)
                       line.append(str(price))
                   # Add row
                   lines.append(','.join(line))
         data = '\n'.join(lines)
         table = import_from_csv(StringIO(data), product_model.name)
         body.append(table)
     # Extport as ODS
     f = StringIO()
     document.save(f)
     content = f.getvalue()
     f.close()
     # Return ODS
     context.set_content_type('application/vnd.oasis.opendocument.spreadsheet')
     context.set_content_disposition('attachment', 'export.ods')
     return content
Exemple #3
0
def init_doc(filename, mimetype):
    if mimetype in (ODF_TEXT, ODF_SPREADSHEET, ODF_PRESENTATION):
        output_doc = odf_get_document(filename)
        if mimetype == ODF_TEXT:
            # Extra for text: begin with a TOC
            output_body = output_doc.get_body()
            output_body.insert(odf_create_toc(), FIRST_CHILD)
    elif mimetype in (CSV_SHORT, CSV_LONG):
        output_doc = odf_new_document_from_type('spreadsheet')
        add_csv(filename, output_doc)
    else:
        raise NotImplementedError, mimetype
    return output_doc
Exemple #4
0
def init_doc(filename, mimetype):
    if mimetype in (ODF_TEXT, ODF_SPREADSHEET, ODF_PRESENTATION):
        output_doc = odf_get_document(filename)
        if mimetype == ODF_TEXT:
            # Extra for text: begin with a TOC
            output_body = output_doc.get_body()
            output_body.insert(odf_create_toc(), FIRST_CHILD)
    elif mimetype in (CSV_SHORT, CSV_LONG):
        output_doc = odf_new_document_from_type('spreadsheet')
        add_csv(filename, output_doc)
    else:
        raise NotImplementedError, mimetype
    return output_doc
Exemple #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
Exemple #6
0
    def action_export(self, resource, context, form):
        root = context.root

        results = context.root.search(format=self.export_resource.class_id)
        if not len(results):
            context.message = ERR_NO_DATA
            return
        context.query['batch_start'] = context.query['batch_size'] = 0

        # Create ODS
        header_style = odf_create_style('table-cell', area='text', bold=True)
        document = odf_new_document_from_type('spreadsheet')
        document.insert_style(header_style, automatic=True)
        body = document.get_body()
        table = odf_create_table(u'Table')

        # Add the header
        row = odf_create_row()
        line = self.get_header(resource, context)
        row.set_values(line, style=header_style)
        table.append_row(row)

        # Fill content
        for item_brain in results.get_documents():
            item_resource = root.get_resource(item_brain.abspath)
            line = self.get_row(resource, context, item_resource)
            row = odf_create_row()
            try:
                row.set_values(line)
            except Exception:
                context.message = ERROR(u'Error on line %s' % line)
                return
            table.append_row(row)

        body.append(table)

        # Extport as ODS
        f = StringIO()
        document.save(f)
        content = f.getvalue()
        f.close()
        # Return ODS
        context.set_content_type(
            'application/vnd.oasis.opendocument.spreadsheet')
        context.set_content_disposition('attachment',
                                        self.get_filename(resource))
        return content
Exemple #7
0
    def action_export(self, resource, context, form):
        root = context.root

        results = context.root.search(format=self.export_resource.class_id)
        if not len(results):
            context.message = ERR_NO_DATA
            return
        context.query['batch_start'] = context.query['batch_size'] = 0

        # Create ODS
        header_style = odf_create_style('table-cell', area='text', bold=True)
        document = odf_new_document_from_type('spreadsheet')
        document.insert_style(header_style, automatic=True)
        body = document.get_body()
        table = odf_create_table(u'Table')

        # Add the header
        row = odf_create_row()
        line = self.get_header(resource, context)
        row.set_values(line, style=header_style)
        table.append_row(row)

        # Fill content
        for item_brain in results.get_documents():
            item_resource = root.get_resource(item_brain.abspath)
            line = self.get_row(resource, context, item_resource)
            row = odf_create_row()
            try:
                row.set_values(line)
            except Exception:
                context.message = ERROR(u'Error on line %s' % line)
                return
            table.append_row(row)

        body.append(table)

        # Extport as ODS
        f = StringIO()
        document.save(f)
        content = f.getvalue()
        f.close()
        # Return ODS
        context.set_content_type('application/vnd.oasis.opendocument.spreadsheet')
        context.set_content_disposition('attachment', self.get_filename(resource))
        return content
Exemple #8
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
def rst2odt(rst_body, template=None):
    """Convert a reStructuredText source to a new document.

    The template is a document to reuse instead of the default lpOD template.

    Arguments:

        rst_body -- str or docutils node

        template -- odf_document

    Return: odf_document
    """
    # Use an existing document structure
    if template is not None:
        document = template.clone()
        # Clean the body
        document.get_body().clear()
    # Or create a new document
    else:
        document = odf_new_document_from_type("text")

    return convert(document, rst_body)
Exemple #10
0
# Import from lpod
from lpod.document import odf_new_document_from_type
from lpod.draw_page import odf_create_draw_page
from lpod.frame import odf_create_text_frame, odf_create_image_frame
from lpod.list import odf_create_list
from lpod.shapes import odf_create_line, odf_create_connector
from lpod.shapes import odf_create_rectangle, odf_create_ellipse
from lpod.style import odf_create_style


PPC = 72 * 2.54


# Creation of the document
document = odf_new_document_from_type('presentation')
body = document.get_body()

# Change the default graphic fill color
standard = document.get_style('graphic', u"standard")
standard.set_style_properties({'draw:fill-color': '#ffffff'})

#
# Work on pages and add textframes
#
page1 = odf_create_draw_page('page1', name=u"Page 1")
body.append(page1)

#
# Text Frame
#
Exemple #11
0
    def action(self, resource, context, form):
        from lpod.document import odf_get_document
        from lpod.document import odf_new_document_from_type
        from lpod.rst2odt import rst2odt, convert, make_context
        from lpod.toc import odf_create_toc

        parent = resource.parent
        template = None
        template_upload = form['template_upload']
        if template_upload is not None:
            filename, mimetype, body = template_upload
            if mimetype not in ALLOWED_FORMATS:
                context.message = ERR_NOT_ODT(filename=filename)
            template = odf_get_document(StringIO(body))
        else:
            template_name = form['template']
            if template_name:
                template_resource = parent.get_resource(template_name)
                body = template_resource.handler.to_str()
                template = odf_get_document(StringIO(body))

        book = resource.get_book()
        if book is not None:
            # Prepare document
            if template is None:
                document = odf_new_document_from_type('text')
            else:
                document = template.clone()
                document.get_body().clear()
            # Metadata
            meta = document.get_meta()
            now = datetime.now()
            meta.set_creation_date(now)
            meta.set_modification_date(now)
            meta.set_editing_duration(timedelta(0))
            meta.set_editing_cycles(1)
            meta.set_generator(u"ikaaro.wiki to ODT")
            for metadata in ('title', 'comments', 'subject', 'language',
                    'keywords'):
                getattr(meta, 'set_' + metadata)(book.get(metadata))
            # Cover page
            cover_uri = book.get('cover')
            if cover_uri:
                cover = parent.get_resource(cover_uri, soft=True)
                if cover is None:
                    if not form['ignore_missing_pages']:
                        context.message = ERR_PAGE_NOT_FOUND(uri=cover_uri)
                        return
                else:
                    doctree = cover.get_doctree()
                    resolve_references(doctree, resource, context)
                    resolve_images(doctree, resource, context)
                    heading_level = 0 if startswith_section(doctree) else 1
                    convert_context = make_context(document,
                            heading_level=heading_level,
                            skip_toc=True,
                            # Override temporarly convert_title
                            convert_title=convert_cover_title,
                            convert_subtitle=convert_cover_title)
                    convert(document, doctree, context=convert_context)
            # Global TOC
            language = book.get('language').split('-')[0]
            title = MSG(u"Table of Contents").gettext(language=language)
            outline_level = book.get('toc-depth', 10)
            toc = odf_create_toc(title=title, outline_level=outline_level)
            document.get_body().append(toc)
            # List of pages and their starting title level
            doctree = resource.get_doctree()
            visitor = PageVisitor(doctree, resource,
                    ignore_missing_pages=form['ignore_missing_pages'])
            try:
                book.walkabout(visitor)
            except LookupError, uri:
                context.message = ERR_PAGE_NOT_FOUND(uri=uri)
                return
            pages = visitor.pages
            if not pages:
                context.message = ERR_NO_PAGE_FOUND
                return
            # List of links between pages
            known_links = [ page.abspath for page, _ in pages ]
            # Compile pages
            for page, level in pages:
                doctree = page.get_doctree()
                try:
                    resolve_references(doctree, page, context,
                            reference_resolver=odt_reference_resolver,
                            known_links=known_links)
                except ValueError, e:
                    context.message = ERROR(unicode(str(e), 'utf_8'))
                    return
                resolve_images(doctree, resource, context)
                if startswith_section(doctree):
                    # convert_section will increment it
                    level -= 1
                convert_context = make_context(document,
                        heading_level=level,
                        skip_toc=True)
                convert(document, doctree, context=convert_context)
Exemple #12
0
#    http://www.apache.org/licenses/LICENSE-2.0
#

# Import from lpod
from lpod.document import odf_new_document_from_type
from lpod.draw_page import odf_create_draw_page
from lpod.frame import odf_create_text_frame, odf_create_image_frame
from lpod.list import odf_create_list
from lpod.shapes import odf_create_line, odf_create_connector
from lpod.shapes import odf_create_rectangle, odf_create_ellipse
from lpod.style import odf_create_style

PPC = 72 * 2.54

# Creation of the document
document = odf_new_document_from_type('presentation')
body = document.get_body()

# Change the default graphic fill color
standard = document.get_style('graphic', u"standard")
standard.set_style_properties({'draw:fill-color': '#ffffff'})

#
# Work on pages and add textframes
#
page1 = odf_create_draw_page('page1', name=u"Page 1")
body.append(page1)

#
# Text Frame
#
Exemple #13
0
    else:
        indoc = odf_get_document(infile)
        intype = indoc.get_type()
    # Open output document
    outfile = args[1]
    if options.styles_from:
        outdoc = odf_get_document(options.styles_from).clone()
        outdoc.get_body().clear()
        outdoc.path = outfile
        outtype = outdoc.get_type()
    else:
        extension = get_extension(outfile)
        try:
            mimetype = ODF_EXTENSIONS[extension]
        except KeyError:
            raise ValueError, "output filename not recognized: " + extension
        outtype = mimetype[mimetype.rindex('.') + 1:]
        if '-template' in outtype:
            outtype = mimetype[mimetype.rindex('-') + 1:]
        outdoc = odf_new_document_from_type(outtype)
    # Convert function
    name = '%s_to_%s' % (intype, outtype)
    converter = getattr(Converter, name, None)
    if converter is None:
        raise NotImplementedError, "unsupported combination"
    # Remove output file
    check_target_file(outfile)
    # Convert!
    converter(indoc, outdoc)
    outdoc.save(outfile)
Exemple #14
0
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#    http://www.apache.org/licenses/LICENSE-2.0
#

# Import from lpod
from lpod.document import odf_new_document_from_type, odf_get_document
from lpod.heading import odf_create_heading
from lpod.list import odf_create_list, odf_create_list_item
from lpod.note import odf_create_note, odf_create_annotation
from lpod.paragraph import odf_create_paragraph
from lpod.table import odf_create_table
from lpod.toc import odf_create_toc

# Creation of the document
document = odf_new_document_from_type('text')
body = document.get_body()

# Add (empty) Table of content
toc = odf_create_toc()
body.append(toc)

# Add Paragraph
paragraph = odf_create_paragraph(u'lpOD generated Document')
body.append(paragraph)

# Add Heading
heading = odf_create_heading(1, text=u'Lists')
body.append(heading)

#
 def test_text_type(self):
     self.assert_(odf_new_document_from_type('text'))
Exemple #16
0
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#    http://www.apache.org/licenses/LICENSE-2.0
#

# Import from the Standard Library
from glob import glob

# Import from lpod
from lpod.document import odf_new_document_from_type
from lpod.frame import odf_create_image_frame
from lpod.paragraph import odf_create_paragraph
from lpod.table import import_from_csv, odf_create_column

# Get elements
document = odf_new_document_from_type('spreadsheet')
body = document.get_body()

for id, filename in enumerate(glob('./files/*.csv')):
    table = import_from_csv(filename, u'Table %s' % (id + 1))

    # Some information
    width = table.get_table_width()
    height = table.get_table_height()

    # Remove empty rows and cells on the edge
    table.rstrip_table()

    # Accessing rows
    first_row = table.get_row(0)
    first_row.set_row_style(u"Another style")
 def test_spreadsheet_type(self):
     self.assert_(odf_new_document_from_type('spreadsheet'))
Exemple #18
0
#    http://www.apache.org/licenses/LICENSE-2.0
#

# Import from Standard Library
from datetime import date
from os.path import normpath, join

# Import from lpod
import lpod
from lpod.document import odf_get_document, odf_new_document_from_type
from lpod.paragraph import odf_create_paragraph
from lpod.style import odf_create_style, odf_create_default_date_style
from lpod.variable import odf_create_date_variable

# Creation of the document
document = odf_new_document_from_type('text')
body = document.get_body()

#
# use merge_styles_from to copy default style from some document
#
path = normpath(join(lpod.__file__, '../templates/lpod_styles.odt'))
doc_style = odf_get_document(path)
document.merge_styles_from(doc_style)

#
# Pages, header and footer
#

# Automatic style to set the master page
style = odf_create_style('paragraph', master_page=u"First_20_Page")
 def action_export_as_ods(self, resource, context, form):
     if lpod_is_install is False:
         msg = ERROR(u'Please install LPOD')
         return context.come_back(msg)
     # XXX Create a new process and send ODS file by mail for performances ?
     # XXX We do not export product without declination
     # XXX We do not export product without product model
     # Get list of groups
     groups = []
     for option in UserGroup_Enumerate.get_options():
         group = context.root.get_resource(option['name'])
         if group.get_property('use_default_price') is True:
             continue
         groups.append(group)
     # DB
     root = context.root
     shop = get_shop(resource)
     document = odf_new_document_from_type('spreadsheet')
     body = document.get_body()
     models = shop.get_resource('products-models').get_resources()
     for product_model in models:
         lines = []
         # We create one TAB by product model
         table = odf_create_table(product_model.get_title())
         search = root.search(
             product_model=str(product_model.get_abspath()))
         for brain in search.get_documents():
             product = root.get_resource(brain.abspath)
             for d in product.search_resources(cls=Declination):
                 # Ref - Declination name - Declination title
                 line = [
                     product.get_property('reference'), d.name,
                     d.get_declination_title().encode('utf-8')
                 ]
                 # Stock
                 line.append(str(d.get_quantity_in_stock()))
                 # Price by group (HT or TTC)
                 for group in groups:
                     k_price = {
                         'id_declination': d.name,
                         'prefix': group.get_prefix(),
                         'pretty': True
                     }
                     if group.get_property('show_ht_price'):
                         price = product.get_price_without_tax(**k_price)
                     else:
                         price = product.get_price_with_tax(**k_price)
                     line.append(str(price))
                 # Add row
                 lines.append(','.join(line))
         data = '\n'.join(lines)
         table = import_from_csv(StringIO(data), product_model.name)
         body.append(table)
     # Extport as ODS
     f = StringIO()
     document.save(f)
     content = f.getvalue()
     f.close()
     # Return ODS
     context.set_content_type(
         'application/vnd.oasis.opendocument.spreadsheet')
     context.set_content_disposition('attachment', 'export.ods')
     return content
Exemple #20
0
    else:
        indoc = odf_get_document(infile)
        intype = indoc.get_type()
    # Open output document
    outfile = args[1]
    if options.styles_from:
        outdoc = odf_get_document(options.styles_from).clone()
        outdoc.get_body().clear()
        outdoc.path = outfile
        outtype = outdoc.get_type()
    else:
        extension = get_extension(outfile)
        try:
            mimetype = ODF_EXTENSIONS[extension]
        except KeyError:
            raise ValueError, "output filename not recognized: " + extension
        outtype = mimetype[mimetype.rindex('.') + 1:]
        if '-template' in outtype:
            outtype = mimetype[mimetype.rindex('-') + 1:]
        outdoc = odf_new_document_from_type(outtype)
    # Convert function
    name = '%s_to_%s' % (intype, outtype)
    converter = getattr(Converter, name, None)
    if converter is None:
        raise NotImplementedError, "unsupported combination"
    # Remove output file
    check_target_file(outfile)
    # Convert!
    converter(indoc, outdoc)
    outdoc.save(outfile)
 def test_drawing_type(self):
     self.assert_(odf_new_document_from_type('drawing'))
 def test_presentation_type(self):
     self.assert_(odf_new_document_from_type('presentation'))