File: rst2odt_prepstyles.py

package info (click to toggle)
python-docutils 0.12+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,108 kB
  • ctags: 7,367
  • sloc: python: 41,778; lisp: 8,644; sh: 164; makefile: 148; xml: 34
file content (85 lines) | stat: -rwxr-xr-x 2,317 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python

# $Id: rst2odt_prepstyles.py 5839 2009-01-07 19:09:28Z dkuhlman $
# Author: Dave Kuhlman <dkuhlman@rexx.com>
# Copyright: This module has been placed in the public domain.

"""
Fix a word-processor-generated styles.odt for odtwriter use: Drop page size
specifications from styles.xml in STYLE_FILE.odt.
"""

#
# Author: Michael Schutte <michi@uiae.at>

try:
    from xml.etree import ElementTree as etree
except ImportError:
    try:
        from elementtree import ElementTree as etree
    except ImportError:
        raise ImportError('Missing an implementation of ElementTree. ' \
                'Please install either Python >= 2.5 or ElementTree.')

import sys
import zipfile
from tempfile import mkstemp
import shutil
import os

NAMESPACES = {
    "style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
    "fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"
}

def prepstyle(filename):
    
    zin = zipfile.ZipFile(filename)
    styles = zin.open("styles.xml")

    root = None
    # some extra effort to preserve namespace prefixes
    for event, elem in etree.iterparse(styles, events=("start", "start-ns")):
        if event == "start-ns":
            etree.register_namespace(elem[0], elem[1])
        elif event == "start":
            if root is None:
                root = elem

    styles.close()

    for el in root.findall(".//style:page-layout-properties",
            namespaces=NAMESPACES):
        for attr in el.attrib.keys():
            if attr.startswith("{%s}" % NAMESPACES["fo"]):
                del el.attrib[attr]
    
    tempname = mkstemp()
    zout = zipfile.ZipFile(os.fdopen(tempname[0], "w"), "w",
        zipfile.ZIP_DEFLATED)
    
    for item in zin.infolist():
        if item.filename == "styles.xml":
            zout.writestr(item, etree.tostring(root, encoding="UTF-8"))
        else:
            zout.writestr(item, zin.read(item.filename))
    
    zout.close()
    zin.close()
    shutil.move(tempname[1], filename)


def main():
    args = sys.argv[1:]
    if len(args) != 1:
        print >> sys.stderr, __doc__
        print >> sys.stderr, "Usage: %s STYLE_FILE.odt\n" % sys.argv[0]
        sys.exit(1)
    filename = args[0]
    prepstyle(filename)

if __name__ == '__main__':
    main()


# vim:tw=78:sw=4:sts=4:et: