Git Product home page Git Product logo

odfpy's Introduction

ODFPY

This is a collection of utility programs written in Python to manipulate OpenDocument 1.2 files.

How to proceed: Each application has its own directory. In there, look at the manual pages. The Python-based tools need the odf library. Just make a symbolic link like this: ln -s ../odf odf ... or type: make

For your own use of the odf library, see api-for-odfpy.odt

INSTALLATION

First you get the package.

$ git clone https://github.com/eea/odfpy.git

Then you can build and install the library for Python2 and Python3:

$ python setup.py build
$ python3 setup.py build
$ su
# python setup.py install
# python3 setup.py install

The library is incompatible with PyXML.

RUNNING TESTS

Install tox via pip when running the tests for the first time:

$ pip install tox

Run the tests for all supported python versions:

$ tox

REDISTRIBUTION LICENSE

This project, with the exception of the OpenDocument schemas, are Copyright (C) 2006-2014, Daniel Carrera, Alex Hudson, Søren Roug, Thomas Zander, Roman Fordinal, Michael Howitz and Georges Khaznadar.

It is distributed under both GNU General Public License v.2 or (at your option) any later version or APACHE License v.2. See GPL-LICENSE-2.txt and APACHE-LICENSE-2.0.txt.

The OpenDocument RelaxNG Schemas are Copyright © OASIS Open 2005. See the schema files for their copyright notice.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

odfpy's People

Contributors

brickxu avatar chfw avatar eugeneai avatar flh avatar galund avatar georgesk avatar graingert avatar interestsfantastic avatar jayvdb avatar joostvanzwieten avatar lixiang2017 avatar mberntsen avatar mhc03 avatar microjosn avatar nadirhamid avatar ramiroluz avatar risicle avatar sorenroug avatar takluyver avatar ubervison avatar ujjwalsh avatar vallon avatar vpoulailleau avatar zimakim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

odfpy's Issues

Adding Frame with a hyperlink

Hello, in LibreOffice we can simply add the frame to ODT Document via Insert->Frame, then add to this Frame hyperlink (in field "Content" of the Frame). Can i do the same using odfpy? (maybe, by draw.Frame, but i don't understand, how exactly)

Pypi release

The latest version of odfpy on Pypi is 0.9.6 - when will a 1.x version be released?

Using with PyInstaller (still) not working

Using version 1.3.5 I get the following error running from a pyinstaller bundle:
...
File "odf/opendocument.py", line 970, in load
File "odf/opendocument.py", line 867, in __loadxmlparts
ImportError: No module named 'load'

Glad to supply any more information if necessary.

Font embedding

I can't see any way of embedding fonts with odfpy, which would be a nice feature.

Proper handling of namespace collision

I just had some problems with draw:frame and namspaces

this element can have both a presentation:style-name and a draw:style-name attribute. the current Element.setAttribute() function will use the first attribute with the name given (in this case draw:) but there is no easy way to access the other attribute. I had to use Element.setAttrNS which is undocumented and doesn't check the grammar

I looked in the api documentation and that sort of conflicts seem common enough that it needs to be dealt with...

I would suggest adding an optional "namespace= namspace.NAME" parameter to setAttribute, maybe make it mandatory for attributes that have a conflict...

Losting images when search and replace text

I am using this solution to search/replace text.

from odf import text, teletype
from odf.opendocument import load

textdoc = load("original.odt")

texts = textdoc.getElementsByType(text.P)
s = len(texts)
for i in range(s):
    old_text = teletype.extractText(texts[i])
    new_text = old_text.replace('my-complexNoRisk-text-to-replace','something else')
    new_S = text.P()
    new_S.setAttribute("stylename",texts[i].getAttribute("stylename"))
    new_S.addText(new_text)
    texts[i].parentNode.insertBefore(new_S,texts[i])
    texts[i].parentNode.removeChild(texts[i])
textdoc.save('myfile.odt')

but myfile.odt is not the expected, losted the image.

Setting paragraph style properties

I'd like to create an amended Text Body style which has large font and some extra spacing below each paragraph.

I've worked out how to set the font size as shown below:

s = newdoc.styles
textbody = Style(name="Text Body", family="paragraph")
textbody.addElement(TextProperties(attributes={'fontsize':"18pt"}))
s.addElement(textbody)

However, I can't see how to set the spacing below the paragraph. I'm assuming it would involve using the ParagraphProperties class, but I can't find any documentation for the parameters of this class, particularly how to set the attribute for paragraph spacing.

missing files?

In odfpy/doc/html/ there is this warning:

Sorry, we had to truncate this directory to 1,000 files. 196 entries were omitted from the list.

I assume that means the 196 files are not only not on the list, they aren't in the repo at all. I would think this is a problem, but I don't see any other reference to a fix. Does this app work without these files? Are they in the repo? etc. Thanks.

Load remove space between user fields

Hi all,

I have a problem when loading/saving a document that contains user fields separated by a space (see variables_with_space.odt in zip archive)
It seems that the call to odf.opendocument.load() deletes the space between the variables.

The odt file has been created with Libreoffice 5.3.1.2

Please see as evidence material, the small program "test_load_save.py" that only load a document and immediately save it.
you can found the result in the file "saved_variables_with_space.odt".

I obtain the same result with various version of odfpy (1.3.4, 1.3.2, 1.2.0) and python (2.7.6, 3.4.4).

It's a very annoying problem as I use the excellent library odfpy to automatically produced reports and this problem makes it useless.
Please, could you help me on that point ?

Best regard,
Davy

bug_report.zip

Example of Setting Borders on Paragraph Style

I would like to add a border above every occurrence of Heading 2 style.

I'm using something like this:

h2style = Style(name="Heading 2", family="paragraph")
pp=ParagraphProperties(attributes={'border':'3pt','borderlinewidthtop':'3pt'})
h2style.addElement(pp)
h2style.addElement(TextProperties(attributes='fontname':'Calibri','fontsize':"10pt",'fontweight':"bold"}))
s.addElement(h2style)

The script runs without errors, and the font attributes are reflected in the .odt document.
However the border doesn't appear.

Has anyone got an example of how to specify the border?
Best wishes
Terry

easyliststyle.py and teletype.py GPL only license?

These files (according to boilerplates) look like pure GPLv2.0 or later. Boilerplates should be fixed (with J. David Eisenberg approval) or these files should be explicitly noticed in README.md (like schemas are).

OpenDocument.save unicode problem

Since OpenDocument.settingsxml() and OpenDocument.metaxml() return a unicode object, it will raise UnicodeEncodeError when running OpenDocument._saveXmlObjects(). The solution is to encode the unicode object in line 677 and 685 in opendocument.py.

line 677
self._z.writestr(zi, anObject.settingsxml() )
Change to
self._z.writestr(zi, anObject.settingsxml().encode('utf8') )

line 685
self._z.writestr(zi, anObject.metaxml() )
Change to
self._z.writestr(zi, anObject.metaxml().encode('utf8') )

parsing ods files with non ascii characters in a formula fails

Similar to #28 if a formula contains a non ascii symbol (for example ="Nöpe") parsing fails:

  File "odf/attrconverters.py", line 113, in __save_prefix
    return str(arg)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in position 6: ordinal not in range(128)

Text:span elements with a space character are treated as self-closed elements

A text span with a space character as content is erroneously treated as a self-closed element without any text. I'm not sure where the problem lies.

This xml in a odf file's content.xml file:
<text:span text:style-name="T1"> </text:span>

Becomes this xml after going through the functions load and toXml:
<text:span text:style-name="T1"/>

I've described the problem more fully at this stack exchange question.

https://stackoverflow.com/q/46049584/621604

DUPLICATE HREF GENERATED IN addPictureFrom*

Functions addPictureFrom* in odf.opendocument use time.time() to gemerate unique filenames. If the functions are called in a loop, this can result in duplicate names due to limited resolution of time.time() in some systems (tested on old Windows Vista PC).

A possible workaraound is the use of uuid module replacing

manifestfn = u"Pictures/%0.0f%s" % ((time.time()*10000000000), ext)

with

manifestfn = u"Pictures/%s%s" % (uuid.uuid4().hex.upper(), ext)

latest odfpy does not work under python 3

Hi all

Here is an overview and odfpy failed to start across python 3 versions. I think it is related to relative imports:

======================================================================
ERROR: Failure: ImportError (No module named 'namespaces')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/nose/failure.py", line 39, in runTest
    raise self.exc_val.with_traceback(self.tb)
  File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/nose/loader.py", line 414, in loadTestsFromName
    addr.filename, addr.module)
  File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/home/travis/virtualenv/python3.3.5/lib/python3.3/imp.py", line 180, in load_module
    return load_source(name, filename, file)
  File "/home/travis/virtualenv/python3.3.5/lib/python3.3/imp.py", line 119, in load_source
    _LoadSourceCompatibility(name, pathname, file).load_module(name)
  File "<frozen importlib._bootstrap>", line 584, in _check_name_wrapper
  File "<frozen importlib._bootstrap>", line 1022, in load_module
  File "<frozen importlib._bootstrap>", line 1003, in load_module
  File "<frozen importlib._bootstrap>", line 560, in module_for_loader_wrapper
  File "<frozen importlib._bootstrap>", line 868, in _load_module
  File "<frozen importlib._bootstrap>", line 313, in _call_with_frames_removed
  File "/home/travis/build/pyexcel/pyexcel-ods/tests/test_bug_fixes.py", line 4, in <module>
    from pyexcel_ods import get_data, save_data
  File "/home/travis/build/pyexcel/pyexcel-ods/pyexcel_ods/__init__.py", line 26, in <module>
    from odf.table import TableRow, TableCell, Table
  File "/home/travis/virtualenv/python3.3.5/lib/python3.3/site-packages/odf/table.py", line 21, in <module>
    from namespaces import TABLENS
ImportError: No module named 'namespaces'

incomplete tarball in release -1.3.1

The tarball at pypi has only doc/latex. The html folder is simply absent. While latex might work, the usual choice of building docs is in html format.

Also the folder manual is missing. Cannot tell whether by accident or intent.

Also from the PKG-INFO
Classifier: Programming Language :: Python :: 2 :: Only
yet from the page https://github.com/eea/odfpy/

"Then you can build and install the library for Python2 and Python3:"
and

"If you run the tests with python3, you will probably see one error. "

Add image to odt

Hi I'm trying to add picture to odt file, but is not working. How I could add image.

from odf.draw import Frame, Image, Page
from odf.style import PageLayout, MasterPage, Header, Footer
from odf.text import P
from odf import table
from datetime import datetime


template = load('/home/bea/Projects/Test Footer/templates/styled-template.odt')

pl = PageLayout(name="pagelayout")
template.automaticstyles.addElement(pl)
mp = MasterPage(name="Standard", pagelayoutname=pl)
page = Page(masterpagename=mp)
template.masterstyles.addElement(mp)

photoframe = Frame(width="200pt", height="200pt", x="56pt", y="56pt")
href = template.addPicture('/home/bea/Projects/Test Footer/code-icon-23069.png')
photoframe.addElement(Image(href=href))
page.addElement(photoframe)

template.save("pic.docx")

Bug tests, no make

The README instruction is "To run the tests, cd into the tests directory and run make". So,

root@User:/sandbox/odfpy#  cd tests/
root@User:/sandbox/odfpy/tests#  make
make: *** ... no file .. ***

wishlist: addressing cells

as a novice user using odfpy to extract data from an .ods file, i found it hard to find cells, skipping over number-columns-repeated etc.

would it be an option to have a helper method on sheets (or other helper function) in the library that allows selecting cells by their coordinates?

odfpy happily inserts illegal xml characters into documents

Beyond escaping, certain ranges of characters are not allowed in xml documents (even if escaped by character code). These are not even allowed in CDATA sections, and the range is even more restrictive due to the use of XML 1.0 (over 1.1).

See https://en.wikipedia.org/wiki/Valid_characters_in_XML

I'm unsure what the right thing for odfpy to do would be when encountering one of these characters. Silently removing the characters seems like bad behaviour. But maybe it should at least raise a ValueError rather than generating an invalid document, leaving the responsibility of stripping/replacing them with the application.

Edit: Though, thinking about this further, it does feel like something that should be quite transparent for an odfpy user - the fact that odf is xml at all is an implementation detail, and a user shouldn't expect to have to do xml escaping to text you're trying to write to an odf.

utf-8 problems - crash ('ascii' codec can't encode in python 2.7, ValueError: '1000000000' not allowed as Boolean value for boolean-value in 3.4)

crash was triggered by

import odf.opendocument
odf.opendocument.load(u'test.ods')

using python 2.7

  File "/usr/local/lib/python2.7/dist-packages/odf/opendocument.py", line 969, in load
    __loadxmlparts(z, manifest, doc, u'')
  File "/usr/local/lib/python2.7/dist-packages/odf/opendocument.py", line 900, in __loadxmlparts
    parser.parse(inpsrc)
  File "/usr/lib/python2.7/xml/sax/expatreader.py", line 107, in parse
    xmlreader.IncrementalParser.parse(self, source)
  File "/usr/lib/python2.7/xml/sax/xmlreader.py", line 123, in parse
    self.feed(buffer)
  File "/usr/lib/python2.7/xml/sax/expatreader.py", line 210, in feed
    self._parser.Parse(data, isFinal)
  File "/usr/lib/python2.7/xml/sax/expatreader.py", line 341, in start_element_ns
    AttributesNSImpl(newattrs, qnames))
  File "/usr/local/lib/python2.7/dist-packages/odf/load.py", line 78, in startElementNS
    e = Element(qname = tag, qattributes=attrdict, check_grammar=False)
  File "/usr/local/lib/python2.7/dist-packages/odf/element.py", line 318, in __init__
    self.setAttrNS(attr[0], attr[1], value)
  File "/usr/local/lib/python2.7/dist-packages/odf/element.py", line 446, in setAttrNS
    self.attributes[(namespace, localpart)] = c.convert((namespace, localpart), value, self)
  File "/usr/local/lib/python2.7/dist-packages/odf/attrconverters.py", line 1607, in convert
    return conversion(attribute, value, element)
  File "/usr/local/lib/python2.7/dist-packages/odf/attrconverters.py", line 41, in cnv_anyURI
    return str(arg)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 103: ordinal not in range(128)

using python3.4

  File "/usr/local/lib/python3.4/dist-packages/odf/opendocument.py", line 969, in load
    __loadxmlparts(z, manifest, doc, u'')
  File "/usr/local/lib/python3.4/dist-packages/odf/opendocument.py", line 900, in __loadxmlparts
    parser.parse(inpsrc)
  File "/usr/lib/python3.4/xml/sax/expatreader.py", line 107, in parse
    xmlreader.IncrementalParser.parse(self, source)
  File "/usr/lib/python3.4/xml/sax/xmlreader.py", line 123, in parse
    self.feed(buffer)
  File "/usr/lib/python3.4/xml/sax/expatreader.py", line 207, in feed
    self._parser.Parse(data, isFinal)
  File "../Modules/pyexpat.c", line 405, in StartElement
  File "/usr/lib/python3.4/xml/sax/expatreader.py", line 341, in start_element_ns
    AttributesNSImpl(newattrs, qnames))
  File "/usr/local/lib/python3.4/dist-packages/odf/load.py", line 78, in startElementNS
    e = Element(qname = tag, qattributes=attrdict, check_grammar=False)
  File "/usr/local/lib/python3.4/dist-packages/odf/element.py", line 318, in __init__
    self.setAttrNS(attr[0], attr[1], value)
  File "/usr/local/lib/python3.4/dist-packages/odf/element.py", line 446, in setAttrNS
    self.attributes[(namespace, localpart)] = c.convert((namespace, localpart), value, self)
  File "/usr/local/lib/python3.4/dist-packages/odf/attrconverters.py", line 1607, in convert
    return conversion(attribute, value, element)
  File "/usr/local/lib/python3.4/dist-packages/odf/attrconverters.py", line 52, in cnv_boolean
    raise ValueError( "'%s' not allowed as Boolean value for %s" % (str(arg), attribute[1]))
ValueError: '1000000000' not allowed as Boolean value for boolean-value

Is this library maintained? If yes I may try reducing my file to a testcase.

KeyError with some ods files

I found this report from two years ago, too:
https://joinup.ec.europa.eu/software/odfpy/issue/mimetype-error-when-working-ods-files-google-drive

I don't know if the file that caused my error is downloaded from google drive or not, but it's the same error.

I can hack around it in my code, but it would be nice to have it fixed, especially since it seems like these files are still readable.

   mimetype = z.read('mimetype')
File '/usr/lib/python2.7/zipfile.py', line 869 in read
  return self.open(name, "r", pwd).read()
File '/usr/lib/python2.7/zipfile.py', line 892 in open
  zinfo = self.getinfo(name)
File '/usr/lib/python2.7/zipfile.py', line 859 in getinfo
  'There is no item named %r in the archive' % name)
KeyError: "There is no item named 'mimetype' in the archive"

Show Stopper: Latest version 1.3.0 breaks on python 2.6

Hi all,

The new release breaks with python 2.6. By the way, is odfpy dropping the support for 2.6?

Cheers.

Traceback (most recent call last):

File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/nose/loader.py", line 414, in loadTestsFromName

addr.filename, addr.module)

File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/nose/importer.py", line 47, in importFromPath

return self.importFromDir(dir_path, fqname)

File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/nose/importer.py", line 94, in importFromDir

mod = load_module(part_fqname, fh, filename, desc)

File "/home/travis/build/chfw/pyexcel-ods/pyexcel_ods/init.py", line 38, in

import odf.opendocument

File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/odf/opendocument.py", line 38, in

import manifest

File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/odf/manifest.py", line 27, in

from element import Element

File "/home/travis/virtualenv/python2.6.9/lib/python2.6/site-packages/odf/element.py", line 33, in

if sys.version_info.major == 3:

AttributeError: 'tuple' object has no attribute 'major'

More details here: https://travis-ci.org/chfw/pyexcel-ods/jobs/64445131

Element.namespaces shouldn't be a class variable

Element.namespaces is a class variable, which means all elements will have the same namespaces even across documents.

This means any document creation will change a global state, which is not only wrong, but makes it hard to test since tests rean't isolated.

The comment is "Due to shallow copy this is a static variable" which doesn't make sense to me, but a simple fix breaks some tests, and I don't know if that's because the tests are wrong or because this has sideeffects that we don't want.

loext and odfpy

I'm looking for "borders for characters" (not for paragraph) : is there a way to create such effect using odfpy ? I asked the same question on stackoverflow : is odfpy able to handle the "loext" keywords (=Libre Office extensions(?)) ?

Thanks !
Xavier

UBUNTU 16 LTS install bug

Using README instructions. After git clone, the python setup.py build shows

user@User:~/sandbox/odfpy$ python setup.py build
/usr/lib/python2.7/dist-packages/setuptools/dist.py:285: UserWarning: Normalizing '1.3.6dev' to '1.3.6.dev0'
  normalized_version,
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/odf
copying odf/manifest.py -> build/lib.linux-x86_64-2.7/odf
copying odf/grammar.py -> build/lib.linux-x86_64-2.7/odf
copying odf/presentation.py -> build/lib.linux-x86_64-2.7/odf
copying odf/dc.py -> build/lib.linux-x86_64-2.7/odf
....
changing mode of build/scripts-2.7/odfuserfield from 664 to 775
changing mode of build/scripts-2.7/xml2odf from 664 to 775

So, seems all fine... But python3 setup.py build

Traceback (most recent call last):
  File "setup.py", line 22, in <module>
    from setuptools import setup
ImportError: No module named 'setuptools'

It is a bug in the instructions or a bug at my UNUNTU...

Test failure in test_xmlgenerator_wo_ns (testxmlgen.TestXMLGenerator)

One test seems broken:

$ python2.7 -m unittest discover tests/
................................................................/Object 1
..........E..........
======================================================================
ERROR: test_xmlgenerator_wo_ns (testxmlgen.TestXMLGenerator)
Test that the missing xml namespace is understood by XMLGenerator
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/joseph/prog/odfpy.git/tests/testxmlgen.py", line 73, in test_xmlgenerator_wo_ns
    parser.feed(testcontent)
  File "/usr/lib/python2.7/site-packages/_xmlplus/sax/expatreader.py", line 216, in feed
    self._parser.Parse(data, isFinal)
  File "/usr/lib/python2.7/site-packages/_xmlplus/sax/expatreader.py", line 353, in start_element_ns
    AttributesNSImpl(newattrs, qnames))
  File "/usr/lib/python2.7/site-packages/_xmlplus/sax/saxutils.py", line 281, in startElementNS
    elif self._current_context[name[0]] is None:
KeyError: u'http://www.w3.org/XML/1998/namespace'

----------------------------------------------------------------------
Ran 85 tests in 1.218s

FAILED (errors=1)

Saving XmlObjects sends Unicode rather than bytes to zipfile

OdfPy expects byte stream, not unicode. Opendocument properties like author created/modified may contain unicode characters, load/save is broken.

def _saveXmlObjects(self, anObject, folder):

-> properly encodes stylesxml() but not contentxml(), settingsxml(), metaxml()

diff --git a/odf/opendocument.py b/odf/opendocument.py
index ac81273..85ab20c 100644
--- a/odf/opendocument.py
+++ b/odf/opendocument.py
@@ -666,7 +666,7 @@ class OpenDocument:
zi = zipfile.ZipInfo(u"%scontent.xml" % folder, self._now)
zi.compress_type = zipfile.ZIP_DEFLATED
zi.external_attr = UNIXPERMS

  •    self._z.writestr(zi, anObject.contentxml() )
    
  •    self._z.writestr(zi, anObject.contentxml().encode("utf-8") )
    
     # Write settings
     if anObject.settings.hasChildNodes():
    

    @@ -674,7 +674,7 @@ class OpenDocument:
    zi = zipfile.ZipInfo(u"%ssettings.xml" % folder, self._now)
    zi.compress_type = zipfile.ZIP_DEFLATED
    zi.external_attr = UNIXPERMS

  •        self._z.writestr(zi, anObject.settingsxml() )
    
  •        self._z.writestr(zi, anObject.settingsxml().encode("utf-8") )
    
     # Write meta
     if self == anObject:
    

    @@ -682,7 +682,7 @@ class OpenDocument:
    zi = zipfile.ZipInfo(u"meta.xml", self._now)
    zi.compress_type = zipfile.ZIP_DEFLATED
    zi.external_attr = UNIXPERMS

  •        self._z.writestr(zi, anObject.metaxml() )
    
  •        self._z.writestr(zi, anObject.metaxml().encode("utf-8") )
    
     # Write subobjects
     subobjectnum = 1
    

How to generate references ?

Dears Contributors,

First, thanks you for this very useful library. However, I have a problem to generate references in ODT document using ReferenceRef (see attached file). I use the following code to produce it :

    p.addElement(ReferenceRef(referenceformat="text", refname="[MYREF]"))

And the result is:
<text:p>Add a reference to <text:reference-ref ns41:e="text" ns41:e="[MYREF]"/></text:p>

Where I expect to obtain:
<text:p>Add a reference to <text:reference-ref refefernce-format="text" refname="[MYREF]"/></text:p>

What's wrong ?

Thanks you
Davy
test_references.txt

Image Attachment fails unicode test in Python 2.7

I noticed that after upgrading to the latest version of odfpy, that attempting to attach images was causing an AssertionError in python 2.7. The issue was that the incoming image path was a python str, but the code in opendocument.py was expecting unicode. In Python 2.7 unicode != str and thus the assert throws an error.

==== Relevant Tracebacks ====

Traceback (most recent call last):
  File "docs/odf_main.py", line 155, in _create_cover_page_header_footer
    LogoHref  = self.odfDoc.addPicture(image_path)
  File "venv/local/lib/python2.7/site-packages/odf/opendocument.py", line 438, in addPicture
    assert(type(mediatype)==type(u""))
AssertionError
File "../venv/local/lib/python2.7/site-packages/odf/opendocument.py", line 572, in save
    assert(type(outputfile)==type(u"") or 'wb' in repr(outputfile) or 'BufferedWriter' in repr(outputfile)  or 'BytesIO' in repr(outputfile))
AssertionError

==== Patch which fixed all problems for me ====

--- opendocument.py.orig    2015-11-04 16:14:44.833193579 -0600
+++ opendocument.py 2015-11-04 16:17:54.570278640 -0600
@@ -426,6 +426,12 @@
                 except: ext=u''
             else:
                 ext = mimetypes.guess_extension(mediatype)
+
+            if type(filename) == type(""):
+                filename  = unicode(filename)
+            if type(mediatype) == type(""):
+                mediatype = unicode(mediatype)
+
             manifestfn = u"Pictures/%0.0f%s" % ((time.time()*10000000000), ext)
             self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype)
             content=b""  # this value is only use by the assert further
@@ -459,6 +465,12 @@
             except ValueError: ext=u''
         else:
             ext = mimetypes.guess_extension(mediatype)
+
+        if type(filename) == type(""):
+            filename  = unicode(filename)
+        if type(mediatype) == type(""):
+            mediatype = unicode(mediatype)
+
         manifestfn = u"Pictures/%0.0f%s" % ((time.time()*10000000000), ext)
         self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype)

@@ -569,6 +581,10 @@
         the ZIP content.
         @param addsuffix boolean: whether to add a suffix or not; defaults to False
         """
+        
+        if type(outputfile) == type(""):
+            outputfile = unicode(outputfile)
+        
         assert(type(outputfile)==type(u"") or 'wb' in repr(outputfile) or 'BufferedWriter' in repr(outputfile)  or 'BytesIO' in repr(outputfile))
         assert(type(addsuffix)==type(True))

Load flat ODT files

I want to include an ODT template in my source control so I use the flat ODT format.

This isn't supported in odfpy :(

>>> load(unicode(pkg_resources.resource_filename('datascience.reports.operational', 'GBP.fods')))
BadZipfile: File is not a zip file

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.