| 1 |
# Copyright (C) 2006-2010 Søren Roug, European Environment Agency |
| 2 |
# |
| 3 |
# This library is free software; you can redistribute it and/or |
| 4 |
# modify it under the terms of the GNU Lesser General Public |
| 5 |
# License as published by the Free Software Foundation; either |
| 6 |
# version 2.1 of the License, or (at your option) any later version. |
| 7 |
# |
| 8 |
# This library is distributed in the hope that it will be useful, |
| 9 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 11 |
# Lesser General Public License for more details. |
| 12 |
# |
| 13 |
# You should have received a copy of the GNU Lesser General Public |
| 14 |
# License along with this library; if not, write to the Free Software |
| 15 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 16 |
# |
| 17 |
# Contributor(s): |
| 18 |
# |
| 19 |
|
| 20 |
|
| 21 |
__doc__ = '''Use OpenDocument to generate your documents.''' |
| 22 |
|
| 23 |
import mimetypes |
| 24 |
import sys |
| 25 |
import time |
| 26 |
import zipfile |
| 27 |
from io import BytesIO |
| 28 |
from xml.sax.xmlreader import InputSource |
| 29 |
|
| 30 |
from polyglot.io import PolyglotBytesIO, PolyglotStringIO |
| 31 |
|
| 32 |
from . import element, manifest, meta |
| 33 |
from .attrconverters import make_NCName |
| 34 |
from .namespaces import CHARTNS, DRAWNS, METANS, OFFICENS, PRESENTATIONNS, STYLENS, TABLENS, TEXTNS, TOOLSVERSION |
| 35 |
from .odfmanifest import manifestlist |
| 36 |
from .office import ( |
| 37 |
AutomaticStyles, |
| 38 |
Body, |
| 39 |
Chart, |
| 40 |
Document, |
| 41 |
DocumentContent, |
| 42 |
DocumentMeta, |
| 43 |
DocumentSettings, |
| 44 |
DocumentStyles, |
| 45 |
Drawing, |
| 46 |
FontFaceDecls, |
| 47 |
Image, |
| 48 |
MasterStyles, |
| 49 |
Meta, |
| 50 |
Presentation, |
| 51 |
Scripts, |
| 52 |
Settings, |
| 53 |
Spreadsheet, |
| 54 |
Styles, |
| 55 |
Text, |
| 56 |
) |
| 57 |
|
| 58 |
__version__ = TOOLSVERSION |
| 59 |
|
| 60 |
_XMLPROLOGUE = "<?xml version='1.0' encoding='UTF-8'?>\n" |
| 61 |
|
| 62 |
UNIXPERMS = 0o100644 << 16 # -rw-r--r-- |
| 63 |
|
| 64 |
IS_FILENAME = 0 |
| 65 |
IS_IMAGE = 1 |
| 66 |
# We need at least Python 2.2 |
| 67 |
assert sys.version_info >= (2, 2) |
| 68 |
|
| 69 |
# sys.setrecursionlimit(100) |
| 70 |
# The recursion limit is set conservative so mistakes like |
| 71 |
# s=content() s.addElement(s) won't eat up too much processor time. |
| 72 |
|
| 73 |
odmimetypes = { |
| 74 |
'application/vnd.oasis.opendocument.text': '.odt', |
| 75 |
'application/vnd.oasis.opendocument.text-template': '.ott', |
| 76 |
'application/vnd.oasis.opendocument.graphics': '.odg', |
| 77 |
'application/vnd.oasis.opendocument.graphics-template': '.otg', |
| 78 |
'application/vnd.oasis.opendocument.presentation': '.odp', |
| 79 |
'application/vnd.oasis.opendocument.presentation-template': '.otp', |
| 80 |
'application/vnd.oasis.opendocument.spreadsheet': '.ods', |
| 81 |
'application/vnd.oasis.opendocument.spreadsheet-template': '.ots', |
| 82 |
'application/vnd.oasis.opendocument.chart': '.odc', |
| 83 |
'application/vnd.oasis.opendocument.chart-template': '.otc', |
| 84 |
'application/vnd.oasis.opendocument.image': '.odi', |
| 85 |
'application/vnd.oasis.opendocument.image-template': '.oti', |
| 86 |
'application/vnd.oasis.opendocument.formula': '.odf', |
| 87 |
'application/vnd.oasis.opendocument.formula-template': '.otf', |
| 88 |
'application/vnd.oasis.opendocument.text-master': '.odm', |
| 89 |
'application/vnd.oasis.opendocument.text-web': '.oth', |
| 90 |
} |
| 91 |
|
| 92 |
|
| 93 |
class OpaqueObject: |
| 94 |
def __init__(self, filename, mediatype, content=None): |
| 95 |
self.mediatype = mediatype |
| 96 |
self.filename = filename |
| 97 |
self.content = content |
| 98 |
|
| 99 |
|
| 100 |
class OpenDocument: |
| 101 |
"""A class to hold the content of an OpenDocument document |
| 102 |
Use the xml method to write the XML |
| 103 |
source to the screen or to a file |
| 104 |
d = OpenDocument(mimetype) |
| 105 |
fd.write(d.xml()) |
| 106 |
""" |
| 107 |
|
| 108 |
thumbnail = None |
| 109 |
# Optional content-type-specific elements set by factory functions or load() |
| 110 |
text: element.Node |
| 111 |
graphics: element.Node |
| 112 |
presentation: element.Node |
| 113 |
spreadsheet: element.Node |
| 114 |
chart: element.Node |
| 115 |
image: element.Node |
| 116 |
formula: element.Node |
| 117 |
drawing: element.Node |
| 118 |
|
| 119 |
def __init__(self, mimetype, add_generator=True): |
| 120 |
self.mimetype = mimetype |
| 121 |
self.childobjects = [] |
| 122 |
self._extra = [] |
| 123 |
self.folder = '' # Always empty for toplevel documents |
| 124 |
self.topnode = Document(mimetype=self.mimetype) |
| 125 |
self.topnode.ownerDocument = self |
| 126 |
|
| 127 |
self.clear_caches() |
| 128 |
|
| 129 |
self.Pictures = {} |
| 130 |
self.meta = Meta() |
| 131 |
self.topnode.addElement(self.meta) |
| 132 |
if add_generator: |
| 133 |
self.meta.addElement(meta.Generator(text=TOOLSVERSION)) |
| 134 |
self.scripts = Scripts() |
| 135 |
self.topnode.addElement(self.scripts) |
| 136 |
self.fontfacedecls = FontFaceDecls() |
| 137 |
self.topnode.addElement(self.fontfacedecls) |
| 138 |
self.settings = Settings() |
| 139 |
self.topnode.addElement(self.settings) |
| 140 |
self.styles = Styles() |
| 141 |
self.topnode.addElement(self.styles) |
| 142 |
self.automaticstyles = AutomaticStyles() |
| 143 |
self.topnode.addElement(self.automaticstyles) |
| 144 |
self.masterstyles = MasterStyles() |
| 145 |
self.topnode.addElement(self.masterstyles) |
| 146 |
self.body = Body() |
| 147 |
self.topnode.addElement(self.body) |
| 148 |
|
| 149 |
def rebuild_caches(self, node=None): |
| 150 |
if node is None: |
| 151 |
node = self.topnode |
| 152 |
self.build_caches(node) |
| 153 |
for e in node.childNodes: |
| 154 |
if e.nodeType == element.Node.ELEMENT_NODE: |
| 155 |
self.rebuild_caches(e) |
| 156 |
|
| 157 |
def clear_caches(self): |
| 158 |
self.element_dict = {} |
| 159 |
self._styles_dict = {} |
| 160 |
self._styles_ooo_fix = {} |
| 161 |
|
| 162 |
def build_caches(self, element): |
| 163 |
"""Called from element.py""" |
| 164 |
if element.qname not in self.element_dict: |
| 165 |
self.element_dict[element.qname] = [] |
| 166 |
self.element_dict[element.qname].append(element) |
| 167 |
if element.qname == (STYLENS, 'style'): |
| 168 |
self.__register_stylename(element) # Add to style dictionary |
| 169 |
styleref = element.getAttrNS(TEXTNS, 'style-name') |
| 170 |
if styleref is not None and styleref in self._styles_ooo_fix: |
| 171 |
element.setAttrNS(TEXTNS, 'style-name', self._styles_ooo_fix[styleref]) |
| 172 |
|
| 173 |
def __register_stylename(self, element): |
| 174 |
"""Register a style. But there are three style dictionaries: |
| 175 |
office:styles, office:automatic-styles and office:master-styles |
| 176 |
Chapter 14 |
| 177 |
""" |
| 178 |
name = element.getAttrNS(STYLENS, 'name') |
| 179 |
if name is None: |
| 180 |
return |
| 181 |
if element.parentNode.qname in ((OFFICENS, 'styles'), (OFFICENS, 'automatic-styles')): |
| 182 |
if name in self._styles_dict: |
| 183 |
newname = 'M' + name # Rename style |
| 184 |
self._styles_ooo_fix[name] = newname |
| 185 |
# From here on all references to the old name will refer to the new one |
| 186 |
name = newname |
| 187 |
element.setAttrNS(STYLENS, 'name', name) |
| 188 |
self._styles_dict[name] = element |
| 189 |
|
| 190 |
def toXml(self, filename=''): |
| 191 |
xml = PolyglotBytesIO() |
| 192 |
xml.write(_XMLPROLOGUE) |
| 193 |
self.body.toXml(0, xml) |
| 194 |
if not filename: |
| 195 |
return xml.getvalue() |
| 196 |
else: |
| 197 |
f = open(filename, 'wb') |
| 198 |
f.write(xml.getvalue()) |
| 199 |
f.close() |
| 200 |
|
| 201 |
def xml(self): |
| 202 |
"""Generates the full document as an XML file |
| 203 |
Always written as a bytestream in UTF-8 encoding |
| 204 |
""" |
| 205 |
self.__replaceGenerator() |
| 206 |
xml = PolyglotBytesIO() |
| 207 |
xml.write(_XMLPROLOGUE) |
| 208 |
self.topnode.toXml(0, xml) |
| 209 |
return xml.getvalue() |
| 210 |
|
| 211 |
def contentxml(self): |
| 212 |
"""Generates the content.xml file |
| 213 |
Always written as a bytestream in UTF-8 encoding |
| 214 |
""" |
| 215 |
xml = PolyglotBytesIO() |
| 216 |
xml.write(_XMLPROLOGUE) |
| 217 |
x = DocumentContent() |
| 218 |
x.write_open_tag(0, xml) |
| 219 |
if self.scripts.hasChildNodes(): |
| 220 |
self.scripts.toXml(1, xml) |
| 221 |
if self.fontfacedecls.hasChildNodes(): |
| 222 |
self.fontfacedecls.toXml(1, xml) |
| 223 |
a = AutomaticStyles() |
| 224 |
stylelist = self._used_auto_styles([self.styles, self.automaticstyles, self.body]) |
| 225 |
if len(stylelist) > 0: |
| 226 |
a.write_open_tag(1, xml) |
| 227 |
for s in stylelist: |
| 228 |
s.toXml(2, xml) |
| 229 |
a.write_close_tag(1, xml) |
| 230 |
else: |
| 231 |
a.toXml(1, xml) |
| 232 |
self.body.toXml(1, xml) |
| 233 |
x.write_close_tag(0, xml) |
| 234 |
return xml.getvalue() |
| 235 |
|
| 236 |
def __manifestxml(self): |
| 237 |
"""Generates the manifest.xml file |
| 238 |
The self.manifest isn't available unless the document is being saved |
| 239 |
""" |
| 240 |
xml = PolyglotBytesIO() |
| 241 |
xml.write(_XMLPROLOGUE) |
| 242 |
self.manifest.toXml(0, xml) |
| 243 |
return xml.getvalue() |
| 244 |
|
| 245 |
def metaxml(self): |
| 246 |
"""Generates the meta.xml file""" |
| 247 |
self.__replaceGenerator() |
| 248 |
x = DocumentMeta() |
| 249 |
x.addElement(self.meta) |
| 250 |
xml = PolyglotStringIO() |
| 251 |
xml.write(_XMLPROLOGUE) |
| 252 |
x.toXml(0, xml) |
| 253 |
return xml.getvalue() |
| 254 |
|
| 255 |
def settingsxml(self): |
| 256 |
"""Generates the settings.xml file""" |
| 257 |
x = DocumentSettings() |
| 258 |
x.addElement(self.settings) |
| 259 |
xml = PolyglotStringIO() |
| 260 |
xml.write(_XMLPROLOGUE) |
| 261 |
x.toXml(0, xml) |
| 262 |
return xml.getvalue() |
| 263 |
|
| 264 |
def _parseoneelement(self, top, stylenamelist): |
| 265 |
"""Finds references to style objects in master-styles |
| 266 |
and add the style name to the style list if not already there. |
| 267 |
Recursive |
| 268 |
""" |
| 269 |
for e in top.childNodes: |
| 270 |
if e.nodeType == element.Node.ELEMENT_NODE: |
| 271 |
for styleref in ( |
| 272 |
(CHARTNS, 'style-name'), |
| 273 |
(DRAWNS, 'style-name'), |
| 274 |
(DRAWNS, 'text-style-name'), |
| 275 |
(PRESENTATIONNS, 'style-name'), |
| 276 |
(STYLENS, 'data-style-name'), |
| 277 |
(STYLENS, 'list-style-name'), |
| 278 |
(STYLENS, 'page-layout-name'), |
| 279 |
(STYLENS, 'style-name'), |
| 280 |
(TABLENS, 'default-cell-style-name'), |
| 281 |
(TABLENS, 'style-name'), |
| 282 |
(TEXTNS, 'style-name'), |
| 283 |
): |
| 284 |
if e.getAttrNS(styleref[0], styleref[1]): |
| 285 |
stylename = e.getAttrNS(styleref[0], styleref[1]) |
| 286 |
if stylename not in stylenamelist: |
| 287 |
stylenamelist.append(stylename) |
| 288 |
stylenamelist = self._parseoneelement(e, stylenamelist) |
| 289 |
return stylenamelist |
| 290 |
|
| 291 |
def _used_auto_styles(self, segments): |
| 292 |
"""Loop through the masterstyles elements, and find the automatic |
| 293 |
styles that are used. These will be added to the automatic-styles |
| 294 |
element in styles.xml |
| 295 |
""" |
| 296 |
stylenamelist = [] |
| 297 |
for top in segments: |
| 298 |
stylenamelist = self._parseoneelement(top, stylenamelist) |
| 299 |
stylelist = [] |
| 300 |
for e in self.automaticstyles.childNodes: |
| 301 |
if e.getAttrNS(STYLENS, 'name') in stylenamelist: |
| 302 |
stylelist.append(e) |
| 303 |
return stylelist |
| 304 |
|
| 305 |
def stylesxml(self): |
| 306 |
"""Generates the styles.xml file""" |
| 307 |
xml = PolyglotStringIO() |
| 308 |
xml.write(_XMLPROLOGUE) |
| 309 |
x = DocumentStyles() |
| 310 |
x.write_open_tag(0, xml) |
| 311 |
if self.fontfacedecls.hasChildNodes(): |
| 312 |
self.fontfacedecls.toXml(1, xml) |
| 313 |
self.styles.toXml(1, xml) |
| 314 |
a = AutomaticStyles() |
| 315 |
a.write_open_tag(1, xml) |
| 316 |
for s in self._used_auto_styles([self.masterstyles]): |
| 317 |
s.toXml(2, xml) |
| 318 |
a.write_close_tag(1, xml) |
| 319 |
if self.masterstyles.hasChildNodes(): |
| 320 |
self.masterstyles.toXml(1, xml) |
| 321 |
x.write_close_tag(0, xml) |
| 322 |
return xml.getvalue() |
| 323 |
|
| 324 |
def addPicture(self, filename, mediatype=None, content=None): |
| 325 |
"""Add a picture |
| 326 |
It uses the same convention as OOo, in that it saves the picture in |
| 327 |
the zipfile in the subdirectory 'Pictures' |
| 328 |
If passed a file ptr, mediatype must be set |
| 329 |
""" |
| 330 |
if content is None: |
| 331 |
if mediatype is None: |
| 332 |
mediatype, encoding = mimetypes.guess_type(filename) |
| 333 |
if mediatype is None: |
| 334 |
mediatype = '' |
| 335 |
try: |
| 336 |
ext = filename[filename.rindex('.') :] |
| 337 |
except Exception: |
| 338 |
ext = '' |
| 339 |
else: |
| 340 |
ext = mimetypes.guess_extension(mediatype) |
| 341 |
manifestfn = f'Pictures/{(time.time() * 10000000000):0.0f}{ext}' |
| 342 |
self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype) |
| 343 |
else: |
| 344 |
manifestfn = filename |
| 345 |
self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype) |
| 346 |
return manifestfn |
| 347 |
|
| 348 |
def addPictureFromFile(self, filename, mediatype=None): |
| 349 |
"""Add a picture |
| 350 |
It uses the same convention as OOo, in that it saves the picture in |
| 351 |
the zipfile in the subdirectory 'Pictures'. |
| 352 |
If mediatype is not given, it will be guessed from the filename |
| 353 |
extension. |
| 354 |
""" |
| 355 |
if mediatype is None: |
| 356 |
mediatype, encoding = mimetypes.guess_type(filename) |
| 357 |
if mediatype is None: |
| 358 |
mediatype = '' |
| 359 |
try: |
| 360 |
ext = filename[filename.rindex('.') :] |
| 361 |
except ValueError: |
| 362 |
ext = '' |
| 363 |
else: |
| 364 |
ext = mimetypes.guess_extension(mediatype) |
| 365 |
manifestfn = f'Pictures/{(time.time() * 10000000000):0.0f}{ext}' |
| 366 |
self.Pictures[manifestfn] = (IS_FILENAME, filename, mediatype) |
| 367 |
return manifestfn |
| 368 |
|
| 369 |
def addPictureFromString(self, content, mediatype): |
| 370 |
"""Add a picture |
| 371 |
It uses the same convention as OOo, in that it saves the picture in |
| 372 |
the zipfile in the subdirectory 'Pictures'. The content variable |
| 373 |
is a string that contains the binary image data. The mediatype |
| 374 |
indicates the image format. |
| 375 |
""" |
| 376 |
ext = mimetypes.guess_extension(mediatype) |
| 377 |
manifestfn = f'Pictures/{(time.time() * 10000000000):0.0f}{ext}' |
| 378 |
self.Pictures[manifestfn] = (IS_IMAGE, content, mediatype) |
| 379 |
return manifestfn |
| 380 |
|
| 381 |
def addThumbnail(self, filecontent): |
| 382 |
"""Add a fixed thumbnail |
| 383 |
The thumbnail in the library is big, so this is pretty useless. |
| 384 |
""" |
| 385 |
self.thumbnail = filecontent |
| 386 |
|
| 387 |
def addObject(self, document, objectname=None): |
| 388 |
"""Adds an object (subdocument). The object must be an OpenDocument class |
| 389 |
The return value will be the folder in the zipfile the object is stored in |
| 390 |
""" |
| 391 |
self.childobjects.append(document) |
| 392 |
if objectname is None: |
| 393 |
document.folder = f'{self.folder}/Object {len(self.childobjects)}' |
| 394 |
else: |
| 395 |
document.folder = objectname |
| 396 |
return f'.{document.folder}' |
| 397 |
|
| 398 |
def _savePictures(self, object, folder): |
| 399 |
for arcname, picturerec in object.Pictures.items(): |
| 400 |
what_it_is, fileobj, mediatype = picturerec |
| 401 |
self.manifest.addElement(manifest.FileEntry(fullpath=f'{folder}{arcname}', mediatype=mediatype)) |
| 402 |
if what_it_is == IS_FILENAME: |
| 403 |
self._z.write(fileobj, arcname, zipfile.ZIP_STORED) |
| 404 |
else: |
| 405 |
zi = zipfile.ZipInfo(str(arcname), self._now) |
| 406 |
zi.compress_type = zipfile.ZIP_STORED |
| 407 |
zi.external_attr = UNIXPERMS |
| 408 |
self._z.writestr(zi, fileobj) |
| 409 |
# According to section 17.7.3 in ODF 1.1, the pictures folder should not have a manifest entry |
| 410 |
# if hasPictures: |
| 411 |
# self.manifest.addElement(manifest.FileEntry(fullpath=f"{folder}Pictures/", mediatype="")) |
| 412 |
# Look in subobjects |
| 413 |
subobjectnum = 1 |
| 414 |
for subobject in object.childobjects: |
| 415 |
self._savePictures(subobject, f'{folder}Object {subobjectnum}/') |
| 416 |
subobjectnum += 1 |
| 417 |
|
| 418 |
def __replaceGenerator(self): |
| 419 |
"""Section 3.1.1: The application MUST NOT export the original identifier |
| 420 |
belonging to the application that created the document. |
| 421 |
""" |
| 422 |
for m in self.meta.childNodes[:]: |
| 423 |
if m.qname == (METANS, 'generator'): |
| 424 |
self.meta.removeChild(m) |
| 425 |
self.meta.addElement(meta.Generator(text=TOOLSVERSION)) |
| 426 |
|
| 427 |
def save(self, outputfile, addsuffix=False): |
| 428 |
"""Save the document under the filename. |
| 429 |
If the filename is '-' then save to stdout |
| 430 |
""" |
| 431 |
if outputfile == '-': |
| 432 |
outputfp = zipfile.ZipFile(sys.stdout.buffer, 'w') |
| 433 |
else: |
| 434 |
if addsuffix: |
| 435 |
outputfile = outputfile + odmimetypes.get(self.mimetype, '.xxx') |
| 436 |
outputfp = zipfile.ZipFile(outputfile, 'w') |
| 437 |
self.__zipwrite(outputfp) |
| 438 |
outputfp.close() |
| 439 |
|
| 440 |
def write(self, outputfp): |
| 441 |
"""User API to write the ODF file to an open file descriptor |
| 442 |
Writes the ZIP format |
| 443 |
""" |
| 444 |
zipoutputfp = zipfile.ZipFile(outputfp, 'w') |
| 445 |
self.__zipwrite(zipoutputfp) |
| 446 |
|
| 447 |
def __zipwrite(self, outputfp): |
| 448 |
"""Write the document to an open file pointer |
| 449 |
This is where the real work is done |
| 450 |
""" |
| 451 |
self._z = outputfp |
| 452 |
self._now = time.localtime()[:6] |
| 453 |
self.manifest = manifest.Manifest() |
| 454 |
|
| 455 |
# Write mimetype |
| 456 |
zi = zipfile.ZipInfo('mimetype', self._now) |
| 457 |
zi.compress_type = zipfile.ZIP_STORED |
| 458 |
zi.external_attr = UNIXPERMS |
| 459 |
self._z.writestr(zi, self.mimetype) |
| 460 |
|
| 461 |
self._saveXmlObjects(self, '') |
| 462 |
|
| 463 |
# Write pictures |
| 464 |
self._savePictures(self, '') |
| 465 |
|
| 466 |
# Write the thumbnail |
| 467 |
if self.thumbnail is not None: |
| 468 |
self.manifest.addElement(manifest.FileEntry(fullpath='Thumbnails/', mediatype='')) |
| 469 |
self.manifest.addElement(manifest.FileEntry(fullpath='Thumbnails/thumbnail.png', mediatype='')) |
| 470 |
zi = zipfile.ZipInfo('Thumbnails/thumbnail.png', self._now) |
| 471 |
zi.compress_type = zipfile.ZIP_DEFLATED |
| 472 |
zi.external_attr = UNIXPERMS |
| 473 |
self._z.writestr(zi, self.thumbnail) |
| 474 |
|
| 475 |
# Write any extra files |
| 476 |
for op in self._extra: |
| 477 |
if op.filename == 'META-INF/documentsignatures.xml': |
| 478 |
continue # Don't save signatures |
| 479 |
self.manifest.addElement(manifest.FileEntry(fullpath=op.filename, mediatype=op.mediatype)) |
| 480 |
zi = zipfile.ZipInfo(op.filename.encode('utf-8'), self._now) |
| 481 |
zi.compress_type = zipfile.ZIP_DEFLATED |
| 482 |
zi.external_attr = UNIXPERMS |
| 483 |
if op.content is not None: |
| 484 |
self._z.writestr(zi, op.content) |
| 485 |
# Write manifest |
| 486 |
zi = zipfile.ZipInfo('META-INF/manifest.xml', self._now) |
| 487 |
zi.compress_type = zipfile.ZIP_DEFLATED |
| 488 |
zi.external_attr = UNIXPERMS |
| 489 |
self._z.writestr(zi, self.__manifestxml()) |
| 490 |
del self._z |
| 491 |
del self._now |
| 492 |
del self.manifest |
| 493 |
|
| 494 |
def _saveXmlObjects(self, object, folder): |
| 495 |
if self == object: |
| 496 |
self.manifest.addElement(manifest.FileEntry(fullpath='/', mediatype=object.mimetype)) |
| 497 |
else: |
| 498 |
self.manifest.addElement(manifest.FileEntry(fullpath=folder, mediatype=object.mimetype)) |
| 499 |
# Write styles |
| 500 |
self.manifest.addElement(manifest.FileEntry(fullpath=f'{folder}styles.xml', mediatype='text/xml')) |
| 501 |
zi = zipfile.ZipInfo(f'{folder}styles.xml', self._now) |
| 502 |
zi.compress_type = zipfile.ZIP_DEFLATED |
| 503 |
zi.external_attr = UNIXPERMS |
| 504 |
self._z.writestr(zi, object.stylesxml()) |
| 505 |
|
| 506 |
# Write content |
| 507 |
self.manifest.addElement(manifest.FileEntry(fullpath=f'{folder}content.xml', mediatype='text/xml')) |
| 508 |
zi = zipfile.ZipInfo(f'{folder}content.xml', self._now) |
| 509 |
zi.compress_type = zipfile.ZIP_DEFLATED |
| 510 |
zi.external_attr = UNIXPERMS |
| 511 |
self._z.writestr(zi, object.contentxml()) |
| 512 |
|
| 513 |
# Write settings |
| 514 |
if object.settings.hasChildNodes(): |
| 515 |
self.manifest.addElement(manifest.FileEntry(fullpath=f'{folder}settings.xml', mediatype='text/xml')) |
| 516 |
zi = zipfile.ZipInfo(f'{folder}settings.xml', self._now) |
| 517 |
zi.compress_type = zipfile.ZIP_DEFLATED |
| 518 |
zi.external_attr = UNIXPERMS |
| 519 |
self._z.writestr(zi, object.settingsxml()) |
| 520 |
|
| 521 |
# Write meta |
| 522 |
if self == object: |
| 523 |
self.manifest.addElement(manifest.FileEntry(fullpath='meta.xml', mediatype='text/xml')) |
| 524 |
zi = zipfile.ZipInfo('meta.xml', self._now) |
| 525 |
zi.compress_type = zipfile.ZIP_DEFLATED |
| 526 |
zi.external_attr = UNIXPERMS |
| 527 |
self._z.writestr(zi, object.metaxml()) |
| 528 |
|
| 529 |
# Write subobjects |
| 530 |
subobjectnum = 1 |
| 531 |
for subobject in object.childobjects: |
| 532 |
self._saveXmlObjects(subobject, f'{folder}Object {subobjectnum}/') |
| 533 |
subobjectnum += 1 |
| 534 |
|
| 535 |
# Document's DOM methods |
| 536 |
def createElement(self, element): |
| 537 |
"""Inconvenient interface to create an element, but follows XML-DOM. |
| 538 |
Does not allow attributes as argument, therefore can't check grammar. |
| 539 |
""" |
| 540 |
return element(check_grammar=False) |
| 541 |
|
| 542 |
def createTextNode(self, data): |
| 543 |
"""Method to create a text node""" |
| 544 |
return element.Text(data) |
| 545 |
|
| 546 |
def createCDATASection(self, data): |
| 547 |
"""Method to create a CDATA section""" |
| 548 |
return element.CDATASection(data) |
| 549 |
|
| 550 |
def getMediaType(self): |
| 551 |
"""Returns the media type""" |
| 552 |
return self.mimetype |
| 553 |
|
| 554 |
def getStyleByName(self, name): |
| 555 |
"""Finds a style object based on the name""" |
| 556 |
ncname = make_NCName(name) |
| 557 |
if self._styles_dict == {}: |
| 558 |
self.rebuild_caches() |
| 559 |
return self._styles_dict.get(ncname, None) |
| 560 |
|
| 561 |
def getElementsByType(self, element): |
| 562 |
"""Gets elements based on the type, which is function from text.py, draw.py etc.""" |
| 563 |
obj = element(check_grammar=False) |
| 564 |
if self.element_dict == {}: |
| 565 |
self.rebuild_caches() |
| 566 |
return self.element_dict.get(obj.qname, []) |
| 567 |
|
| 568 |
|
| 569 |
# Convenience functions |
| 570 |
|
| 571 |
|
| 572 |
def OpenDocumentChart(): |
| 573 |
"""Creates a chart document""" |
| 574 |
doc = OpenDocument('application/vnd.oasis.opendocument.chart') |
| 575 |
doc.chart = Chart() |
| 576 |
doc.body.addElement(doc.chart) |
| 577 |
return doc |
| 578 |
|
| 579 |
|
| 580 |
def OpenDocumentDrawing(): |
| 581 |
"""Creates a drawing document""" |
| 582 |
doc = OpenDocument('application/vnd.oasis.opendocument.graphics') |
| 583 |
doc.drawing = Drawing() |
| 584 |
doc.body.addElement(doc.drawing) |
| 585 |
return doc |
| 586 |
|
| 587 |
|
| 588 |
def OpenDocumentImage(): |
| 589 |
"""Creates an image document""" |
| 590 |
doc = OpenDocument('application/vnd.oasis.opendocument.image') |
| 591 |
doc.image = Image() |
| 592 |
doc.body.addElement(doc.image) |
| 593 |
return doc |
| 594 |
|
| 595 |
|
| 596 |
def OpenDocumentPresentation(): |
| 597 |
"""Creates a presentation document""" |
| 598 |
doc = OpenDocument('application/vnd.oasis.opendocument.presentation') |
| 599 |
doc.presentation = Presentation() |
| 600 |
doc.body.addElement(doc.presentation) |
| 601 |
return doc |
| 602 |
|
| 603 |
|
| 604 |
def OpenDocumentSpreadsheet(): |
| 605 |
"""Creates a spreadsheet document""" |
| 606 |
doc = OpenDocument('application/vnd.oasis.opendocument.spreadsheet') |
| 607 |
doc.spreadsheet = Spreadsheet() |
| 608 |
doc.body.addElement(doc.spreadsheet) |
| 609 |
return doc |
| 610 |
|
| 611 |
|
| 612 |
def OpenDocumentText(): |
| 613 |
"""Creates a text document""" |
| 614 |
doc = OpenDocument('application/vnd.oasis.opendocument.text') |
| 615 |
doc.text = Text() |
| 616 |
doc.body.addElement(doc.text) |
| 617 |
return doc |
| 618 |
|
| 619 |
|
| 620 |
def OpenDocumentTextMaster(): |
| 621 |
"""Creates a text master document""" |
| 622 |
doc = OpenDocument('application/vnd.oasis.opendocument.text-master') |
| 623 |
doc.text = Text() |
| 624 |
doc.body.addElement(doc.text) |
| 625 |
return doc |
| 626 |
|
| 627 |
|
| 628 |
def __loadxmlparts(z, manifest, doc, objectpath): |
| 629 |
from xml.sax import handler, make_parser |
| 630 |
|
| 631 |
from .load import LoadParser |
| 632 |
|
| 633 |
for xmlfile in ( |
| 634 |
objectpath + 'settings.xml', |
| 635 |
objectpath + 'meta.xml', |
| 636 |
objectpath + 'content.xml', |
| 637 |
objectpath + 'styles.xml', |
| 638 |
): |
| 639 |
if xmlfile not in manifest: |
| 640 |
continue |
| 641 |
try: |
| 642 |
xmlpart = z.read(xmlfile) |
| 643 |
doc._parsing = xmlfile |
| 644 |
|
| 645 |
parser = make_parser() |
| 646 |
parser.setFeature(handler.feature_namespaces, 1) |
| 647 |
parser.setContentHandler(LoadParser(doc)) |
| 648 |
parser.setErrorHandler(handler.ErrorHandler()) |
| 649 |
|
| 650 |
inpsrc = InputSource() |
| 651 |
inpsrc.setByteStream(BytesIO(xmlpart)) |
| 652 |
parser.setFeature(handler.feature_external_ges, False) # Changed by Kovid to ignore external DTDs |
| 653 |
parser.parse(inpsrc) |
| 654 |
del doc._parsing |
| 655 |
except KeyError: |
| 656 |
pass |
| 657 |
|
| 658 |
|
| 659 |
def load(odffile): |
| 660 |
"""Load an ODF file into memory |
| 661 |
Returns a reference to the structure |
| 662 |
""" |
| 663 |
z = zipfile.ZipFile(odffile) |
| 664 |
try: |
| 665 |
mimetype = z.read('mimetype') |
| 666 |
except KeyError: # Added by Kovid to handle malformed odt files |
| 667 |
mimetype = 'application/vnd.oasis.opendocument.text' |
| 668 |
doc = OpenDocument(mimetype, add_generator=False) |
| 669 |
|
| 670 |
# Look in the manifest file to see if which of the four files there are |
| 671 |
manifestpart = z.read('META-INF/manifest.xml') |
| 672 |
manifest = manifestlist(manifestpart) |
| 673 |
__loadxmlparts(z, manifest, doc, '') |
| 674 |
for mentry, mvalue in manifest.items(): |
| 675 |
if mentry[:9] == 'Pictures/' and len(mentry) > 9: |
| 676 |
doc.addPicture(mvalue['full-path'], mvalue['media-type'], z.read(mentry)) |
| 677 |
elif mentry == 'Thumbnails/thumbnail.png': |
| 678 |
doc.addThumbnail(z.read(mentry)) |
| 679 |
elif mentry in ('settings.xml', 'meta.xml', 'content.xml', 'styles.xml'): |
| 680 |
pass |
| 681 |
# Load subobjects into structure |
| 682 |
elif mentry[:7] == 'Object ' and len(mentry) < 11 and mentry[-1] == '/': |
| 683 |
subdoc = OpenDocument(mvalue['media-type'], add_generator=False) |
| 684 |
doc.addObject(subdoc, '/' + mentry[:-1]) |
| 685 |
__loadxmlparts(z, manifest, subdoc, mentry) |
| 686 |
elif mentry[:7] == 'Object ': |
| 687 |
pass # Don't load subobjects as opaque objects |
| 688 |
elif mvalue['full-path'][-1] == '/': |
| 689 |
doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], None)) |
| 690 |
else: |
| 691 |
doc._extra.append(OpaqueObject(mvalue['full-path'], mvalue['media-type'], z.read(mentry))) |
| 692 |
# Add the SUN junk here to the struct somewhere |
| 693 |
# It is cached data, so it can be out-of-date |
| 694 |
z.close() |
| 695 |
b = doc.getElementsByType(Body) |
| 696 |
if mimetype[:39] == 'application/vnd.oasis.opendocument.text': |
| 697 |
doc.text = b[0].firstChild |
| 698 |
elif mimetype[:43] == 'application/vnd.oasis.opendocument.graphics': |
| 699 |
doc.graphics = b[0].firstChild |
| 700 |
elif mimetype[:47] == 'application/vnd.oasis.opendocument.presentation': |
| 701 |
doc.presentation = b[0].firstChild |
| 702 |
elif mimetype[:46] == 'application/vnd.oasis.opendocument.spreadsheet': |
| 703 |
doc.spreadsheet = b[0].firstChild |
| 704 |
elif mimetype[:40] == 'application/vnd.oasis.opendocument.chart': |
| 705 |
doc.chart = b[0].firstChild |
| 706 |
elif mimetype[:40] == 'application/vnd.oasis.opendocument.image': |
| 707 |
doc.image = b[0].firstChild |
| 708 |
elif mimetype[:42] == 'application/vnd.oasis.opendocument.formula': |
| 709 |
doc.formula = b[0].firstChild |
| 710 |
return doc |
| 711 |
|
| 712 |
|
| 713 |
# vim: set expandtab sw=4 : |