def action_import_ods(self, resource, context, form): # Check if lpod is install ? if lpod_is_install is False: msg = ERROR(u'Please install LPOD') return context.come_back(msg) # Get models root = context.root shop = get_shop(resource) models = shop.get_resource('products-models').get_resources() # Open ODF file filename, mimetype, body = form['file'] f = StringIO(body) document = odf_get_document(f) for table in document.get_body().get_tables(): model_name = table.get_name() csv = CSVFile(string=table.to_csv()) for row in csv.get_rows(): reference = row[0] declination_name = row[1] stock = row[-3] price1 = row[-2] price2 = row[-1] product_brains = root.search( reference=reference).get_documents() if len(product_brains) > 1: print 'Reference %s %s' % (reference, len(product_brains)) continue product_brain = product_brains[0] product = root.get_resource(product_brain.abspath) declination = product.get_resource(declination_name) # Set change declination.set_property('stock-quantity', int(stock)) context.message = MSG(u'Import has been done') return
def get_slides_deck(decks_and_slides, output): new_deck = odf_new_document('presentation') new_deck.delete_styles() new_deck_body = new_deck.get_body() new_deck_manifest = new_deck.get_part(ODF_MANIFEST) for deck_and_slides in decks_and_slides: deck = odf_get_document(deck_and_slides.deck) if deck == None: continue new_deck.merge_styles_from(deck) deck_body = deck.get_body() deck_manifest = deck.get_part(ODF_MANIFEST) for slide in deck_and_slides.slides: try: slide_position = int(slide) - 1 # Assuming index starts with 1 source_slide = deck_body.get_draw_page(position = slide_position) except: continue if source_slide == None: continue # Copy Images for image in source_slide.get_images(): uri = image.get_url() media_type = deck_manifest.get_media_type(uri) new_deck_manifest.add_full_path(uri, media_type) new_deck.set_part(uri, deck.get_part(uri)) new_deck_body.append(source_slide.clone()) new_deck.save(target=output, pretty=True)
def parse_odf_pics(path, dest_dir=default_dest_dir): """ Using LPOD for: - open possible ODF document: odf_get_document (including URI) - find images inside the document: get_image_list, get_attribute """ lst = os.path.basename(path).split(".") suffix = lst[-1].lower() if not suffix.startswith('od'): return try: document = odf_get_document(path) except: return global counter_odf global counter_outside counter_odf += 1 #for image in document.get_body().get_image_list(): # 092 for image in document.get_body().get_images(): #href = image.get_attribute("xlink:href") # 092 image_url = image.get_url() if not image_url: continue try: image_content = document.get_part(image_url) except KeyError: print "- not found inside document:", path print " image URL:", image_url counter_outside += 1 continue image_name = image_url.split('/')[-1] if check_known(image_content): store_image(path, image_name, image_content, dest_dir)
def create_document(): my_document = odf_new_document('text') style_filename = "estils/estils_programa.odt" style_document = odf_get_document(style_filename) my_document.delete_styles() my_document.merge_styles_from(style_document) return my_document
def parse_odp(path, dest_presentation): """ Using LPOD for: - open possible ODP document: odf_get_document - copy content and merge styles """ lst = os.path.basename(path).split(".") suffix = lst[-1].lower() if suffix != "odp" : return # Check the document unicity if not check_known(path): return try: document = odf_get_document(path) except: return global counter_odp counter_odp += 1 # merge styles dest_presentation.merge_styles_from(document) # add all slides dest_body = dest_presentation.get_body() dest_manifest = dest_presentation.get_part(ODF_MANIFEST) manifest = document.get_part(ODF_MANIFEST) slides = document.get_body().get_draw_pages() for slide in slides: slide = slide.clone() # dont forget images: for image in slide.get_images(): uri = image.get_url() media_type = manifest.get_media_type(uri) dest_manifest.add_full_path(uri, media_type) dest_presentation.set_part(uri, document.get_part(uri)) # append slide, expecting nothing good about its final style dest_body.append(slide)
def get_slides_deck(decks_and_slides, output): new_deck = odf_new_document('presentation') new_deck.delete_styles() new_deck_body = new_deck.get_body() new_deck_manifest = new_deck.get_part(ODF_MANIFEST) for deck_and_slides in decks_and_slides: deck = odf_get_document(deck_and_slides.deck) if deck == None: continue new_deck.merge_styles_from(deck) deck_body = deck.get_body() deck_manifest = deck.get_part(ODF_MANIFEST) for slide in deck_and_slides.slides: try: slide_position = int(slide) - 1 # Assuming index starts with 1 source_slide = deck_body.get_draw_page(position=slide_position) except: continue if source_slide == None: continue # Copy Images for image in source_slide.get_images(): uri = image.get_url() media_type = deck_manifest.get_media_type(uri) new_deck_manifest.add_full_path(uri, media_type) new_deck.set_part(uri, deck.get_part(uri)) new_deck_body.append(source_slide.clone()) new_deck.save(target=output, pretty=True)
def add_odp(filename, output_doc): document = odf_get_document(filename) # Add the pages output_body = output_doc.get_body() already_names = set([ page.get_name() for page in output_body.get_draw_pages() ]) odp_body = document.get_body() for page in odp_body.get_draw_pages(): name = page.get_name() if name in already_names: i = 1 while True: new_name = u"%s_%d" % (name, i) if new_name not in already_names: name = new_name break i += 1 page.set_name(name) already_names.add(name) output_body.append(page) # Add pictures/ _add_pictures(document, output_doc)
def setUp(self): document = odf_get_document('samples/frame_image.odp') self.body = document.get_body() self.size = size = ('1cm', '2mm') self.position = position = ('3in', '4pt') self.frame = odf_create_frame(size=size, position=position, anchor_type='paragraph')
def action_import_ods(self, resource, context, form): # Check if lpod is install ? if lpod_is_install is False: msg = ERROR(u'Please install LPOD') return context.come_back(msg) # Get models root = context.root shop = get_shop(resource) models = shop.get_resource('products-models').get_resources() # Open ODF file filename, mimetype, body = form['file'] f = StringIO(body) document = odf_get_document(f) for table in document.get_body().get_tables(): model_name = table.get_name() csv = CSVFile(string=table.to_csv()) for row in csv.get_rows(): reference = row[0] declination_name = row[1] stock = row[-3] price1 = row[-2] price2 = row[-1] product_brains = root.search(reference=reference).get_documents() if len(product_brains) > 1: print 'Reference %s %s' % (reference, len(product_brains)) continue product_brain = product_brains[0] product = root.get_resource(product_brain.abspath) declination = product.get_resource(declination_name) # Set change declination.set_property('stock-quantity', int(stock)) context.message = MSG(u'Import has been done') return
def add_odp(filename, output_doc): document = odf_get_document(filename) # Add the pages output_body = output_doc.get_body() already_names = set( [page.get_name() for page in output_body.get_draw_pages()]) odp_body = document.get_body() for page in odp_body.get_draw_pages(): name = page.get_name() if name in already_names: i = 1 while True: new_name = "%s_%d" % (name, i) if new_name not in already_names: name = new_name break i += 1 page.set_name(name) already_names.add(name) output_body.append(page) # Add pictures/ _add_pictures(document, output_doc)
def test_save_nogenerator(self): document = self.document temp = StringIO() document.save(temp) temp.seek(0) new = odf_get_document(temp) generator = new.get_part(ODF_META).get_generator() self.assert_(generator.startswith(u"lpOD Python"))
def test_ftp(self): ftp = FTP('ftp.lpod-project.org') ftp.login() file = StringIO() ftp.retrbinary('RETR example.odt', file.write) ftp.quit() file.seek(0) document = odf_get_document(file) self.assertEqual(document.get_mimetype(), ODF_EXTENSIONS['odt'])
def odf_get_document_extend(filename): result = urlsplit(filename) scheme = result.scheme if not scheme: file = open(filename) else: file = urlopen(filename) document = odf_get_document(file) # open the document with lpod return document
def test_save_generator(self): document = self.document.clone() document.get_part(ODF_META).set_generator(u"toto") temp = StringIO() document.save(temp) temp.seek(0) new = odf_get_document(temp) generator = new.get_part(ODF_META).get_generator() self.assertEqual(generator, u"toto")
def setUp(self): self.document = odf_get_document("samples/toc.odt") self.expected = [ "Table des matières", "1. Level 1 title 1", "1.1. Level 2 title 1", "2. Level 1 title 2", "2.1.1. Level 3 title 1", "2.2. Level 2 title 2", "3. Level 1 title 3", "3.1. Level 2 title 1", "3.1.1. Level 3 title 1", "3.1.2. Level 3 title 2", "3.2. Level 2 title 2", "3.2.1. Level 3 title 1", "3.2.2. Level 3 title 2" ]
def merge_styles(document, from_file, target=None, pretty=True): source = odf_get_document(from_file) document.delete_styles() document.merge_styles_from(source) type = document.get_type() # Enhance Presentation merge if type in ('presentation', 'presentation-template'): printinfo("merging presentation styles...") merge_presentation_styles(document, source) document.save(target=target, pretty=pretty) printinfo("Done (0 error, 0 warning).")
def merge_styles(document, from_file, target=None, pretty=True): source = odf_get_document(from_file) document.delete_styles() document.merge_styles_from(source) type = document.get_type() # Enhance Presentation merge if type in ("presentation", "presentation-template"): printinfo("merging presentation styles...") merge_presentation_styles(document, source) document.save(target=target, pretty=pretty) printinfo("Done (0 error, 0 warning).")
def setTemplate(self): if self.output == u'': self.output = self.nfe_id + '.ods' if os.path.exists(self.template_path): self.tmp_path = os.path.join(os.environ['TMPDIR'], self.output.replace('.pdf', '.ods')) shutil.copyfile( self.template_path, self.tmp_path) self.danfe = odf_get_document(self.tmp_path) else: print self.template_path raise OdfTemplateNotFound
def setUp(self): self.document = document = odf_get_document('samples/note.odt') self.body = document.get_body() expected = ('<text:note text:note-class="footnote" text:id="note1">' '<text:note-citation>1</text:note-citation>' '<text:note-body>' '<text:p>' 'a footnote' '</text:p>' '</text:note-body>' '</text:note>') self.expected = expected
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('spreadsheet') add_csv(filename, output_doc) else: raise NotImplementedError(mimetype) return output_doc
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('spreadsheet') add_csv(filename, output_doc) else: raise NotImplementedError, mimetype return output_doc
def extract_document_fields(self, path): """Extract fields from ODF template, return as list of field names.""" from lpod.document import odf_get_document document = odf_get_document(path) content = document.get_content() body = content.get_body() fields = body.get_user_field_decl_list() return [ (item.get_attribute("text:name"), item.get_attribute("office:value-type")) for item in fields ]
def setUp(self): self.document = document = odf_get_document("samples/note.odt") self.body = document.get_body() expected = ( '<text:note text:note-class="footnote" text:id="note1">' "<text:note-citation>1</text:note-citation>" "<text:note-body>" "<text:p>" "a footnote" "</text:p>" "</text:note-body>" "</text:note>" ) self.expected = expected
def add_ods(filename, output_doc): document = odf_get_document(filename) # Add the sheets output_body = output_doc.get_body() ods_body = document.get_body() for table in ods_body.get_tables(): name = table.get_name() name = _get_table_name(name, output_body) table.set_name(name) output_body.append(table) # Add pictures/ _add_pictures(document, output_doc)
def add_odt(filename, output_doc): document = odf_get_document(filename) # Copy content src_body = document.get_body() output_body = output_doc.get_body() for element in src_body.get_children(): tagname = element.get_tag() # Skip TOC, etc. if tagname in ('text:sequence-decls', 'text:table-of-content'): continue # Copy the rest recursively output_body.append(element.clone()) # Add pictures/ _add_pictures(document, output_doc)
def load_spreadsheet(filename): '''Loads all of the sheets in a .ods spreadsheet file. Returns a dictionary of sheet names mapped to row lists. ''' # Store all sheets here sheets = {} # Open document and get content body document = odf_get_document(filename) body = document.get_content().get_body() # Load all sheets for table in body.get_table_list(): sheets[table.get_name()] = load_table(table) return sheets
def setUp(self): self.document = odf_get_document("samples/toc.odt") self.expected = [ u"Table des matières", u"1. Level 1 title 1", u"1.1. Level 2 title 1", u"2. Level 1 title 2", u"2.1.1. Level 3 title 1", u"2.2. Level 2 title 2", u"3. Level 1 title 3", u"3.1. Level 2 title 1", u"3.1.1. Level 3 title 1", u"3.1.2. Level 3 title 2", u"3.2. Level 2 title 2", u"3.2.1. Level 3 title 1", u"3.2.2. Level 3 title 2"]
def set_infos(path, chk_footprint, title, description): """ Using LPOD for: - open possible ODF document: odf_get_document - find images inside the document: get_images - set title and description if image matches """ lst = os.path.basename(path).split(".") suffix = lst[-1].lower() if not suffix.startswith('od'): return try: document = odf_get_document(path) except: return global counter_image global counter_odf global counter_hit counter_odf += 1 document_changed = False for image in document.get_body().get_images(): image_url = image.get_url() if not image_url: continue try: image_content = document.get_part(image_url) except KeyError: print "- not found inside document:", path, print " image URL:", image_url continue counter_image += 1 footprint = make_footprint(image_content) if footprint == chk_footprint: counter_hit += 1 frame = image.get_parent() frame.set_svg_title(title) frame.set_svg_description(description) document_changed = True if document_changed: lst = path.split(".") lst.insert(-1, modified_file_suffix) new_name = '.'.join(lst) print new_name document.save(new_name)
def do_import(self, resource, data, form, template_name): """Format the content of a rst book and create related resources. """ # Get the document from lpod.document import odf_get_document document = odf_get_document(StringIO(data)) # Auto clean the document from lpod.cleaner import clean_document document, _ = clean_document(document) # Make the book cover, links, toc_depth = _format_content(resource, document, template_name, form['max_level']) language = self.get_language(form['language']) meta = _format_meta(form, template_name, toc_depth, language, document) return u' `%s`_\n%s\n%s' % (cover, meta, links)
def replace_odf_pics(path, old_footprint, new_content): """ Using LPOD for: - open possible ODF document: odf_get_document - find images inside the document: get_images - replace images matching old_image by the new one """ lst = os.path.basename(path).split(".") suffix = lst[-1].lower() if not suffix.startswith('od'): return try: document = odf_get_document(path) except: return global counter_image global counter_odf global counter_hit counter_odf += 1 document_changed = False for image in document.get_body().get_images(): image_url = image.get_url() if not image_url: continue try: image_content = document.get_part(image_url) except KeyError: print "- not found inside document:", path, print " image URL:", image_url continue counter_image += 1 footprint = make_footprint(image_content) if footprint == old_footprint: counter_hit += 1 document.set_part(image_url, new_content) document_changed = True if document_changed: lst = path.split(".") lst.insert(-1, modified_file_suffix) new_name = '.'.join(lst) print new_name document.save(new_name)
def setUp(self): self.document = odf_get_document('samples/frame_image.odp') self.manifest = self.document.get_part(ODF_MANIFEST) self.image_path = 'Pictures/10000000000001D40000003C8B3889D9.png'
def setUp(self): self.document = odf_get_document('../lpod/templates/lpod_styles.odt')
def test_filesystem(self): path = 'samples/example.odt' self.assert_(odf_get_document(path))
def setUp(self): self.document = document = odf_get_document("samples/example.odt") self.styles = document.get_styles()
def setUp(self): self.document = odf_get_document('samples/example.odt')
def setUp(self): self.document = document = odf_get_document('samples/span_style.odt') self.body = document.get_body()
elif result.username: if result.port: netloc = '%s:%s' % (result.hostname, result.port) else: netloc = result.hostname url = urlunsplit( (scheme, netloc, result.path, result.query, result.fragment)) password_mgr = HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, url, result.username, result.password) handler = HTTPBasicAuthHandler(password_mgr) opener = build_opener(handler) file = opener.open(url) else: file = urlopen(filename) input_document = odf_get_document(file) # Page page = odf_create_draw_page(name=u"page%d" % (i + 1), master_page=first_master_page) # Title Frame title_frame = get_title_frame(first_master_page) name = unicode(filename.split('/')[-1]) source = u"filesystem" if not scheme else scheme title_frame.set_text_content(u"%s (%s)" % (name, source)) page.append(title_frame) # Get info info = [] input_meta = input_document.get_part(ODF_META) info.append(u"Title: %s" % input_meta.get_title()) stats = input_meta.get_statistic() info.append(u"# pages: %s" % stats['meta:page-count'])
def setUp(self): self.document = document = odf_get_document('samples/base_shapes.odg') self.content = document.get_content()
import os from lpod.document import odf_get_document # ODF export of Wikipedia article Hitchhiker's Guide to the Galaxy (CC-By-SA) filename = "collection2.odt" # For convenience we use some remote access to the document #from urllib2 import urlopen #filename = urlopen("http://arsaperta.org/collection2.odt") style_filename = "lpod_styles.odt" # from the LPOD package # We want to change the styles of the collection2.odt. # We know the lpod_styles.odt document contains an interesting style. # So let’s first fetch the style: style_document = odf_get_document(style_filename) # Open our document: document = odf_get_document(filename) # We could change only some styles, but here we want a clean basis: document.delete_styles() # And now the actual style change: document.merge_styles_from(style_document) if not os.path.exists('test_output'): os.mkdir('test_output') # Saving the document (with a different name) document.save(target=os.path.join('test_output', "my_collection_styled.odt"),
parser.add_option("-s", "--styles", dest="styles_from", metavar="FILE", help=help) # Parse ! options, args = parser.parse_args() # Container if len(args) != 2: parser.print_help() exit(1) # Open input document infile = args[0] extension = get_extension(infile) if extension == 'rst': indoc = open(infile, 'rb').read() intype = 'rst' else: indoc = odf_get_document(infile) intype = indoc.get_type() # Open output document outfile = args[1] extension = get_extension(outfile) if extension in ('csv', 'html', 'rst', 'txt'): check_target_file(outfile) target_file_checked = True outdoc = open(outfile, 'wb') outtype = extension else: if options.styles_from: outdoc = odf_get_document(options.styles_from).clone() outdoc.get_body().clear() outdoc.path = outfile outtype = outdoc.get_type()
def setUp(self): self.doc = odf_get_document("samples/example.odt")
def setUp(self): self.document = odf_get_document('../templates/lpod_styles.odt')
def setUp(self): self.document = document = odf_get_document('samples/frame_image.odp') self.body = document.get_body() self.path = 'Pictures/10000000000001D40000003C8B3889D9.png'
def test_odf_xml(self): path = 'samples/example.xml' self.assert_(odf_get_document(path))
from optparse import OptionParser from sys import exit # Import from lpod from lpod import __version__ from lpod.document import odf_get_document from lpod.cleaner import clean_document if __name__ == '__main__': # Options initialisation usage = "%prog <input.odt> <output.odt>" description = "Clean malformed ODT documents" parser = OptionParser(usage, version=__version__, description=description) # Parse ! options, args = parser.parse_args() # Go ! if len(args) != 2: parser.print_help() exit(1) indoc = odf_get_document(args[0]) outdoc, error_nb = clean_document(indoc) if error_nb != 0: print('%d error(s) fixed.' % error_nb) outdoc.save(target=args[1])