~openerp-community/openobject-addons/taktik

« back to all changes in this revision

Viewing changes to report_openoffice/DocumentConverter.py

  • Committer: Fabien Lydoire
  • Date: 2010-06-18 09:43:14 UTC
  • Revision ID: fl@taktik.be-20100618094314-rsei1ysqf6uwz6nf
added account reports in xls

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
#
 
3
# PyODConverter (Python OpenDocument Converter) v1.0.0 - 2008-05-05
 
4
#
 
5
# This script converts a document from one office format to another by
 
6
# connecting to an OpenOffice.org instance via Python-UNO bridge.
 
7
#
 
8
# Copyright (C) 2008 Mirko Nasato <mirko@artofsolving.com>
 
9
#                    Matthew Holloway <matthew@holloway.co.nz>
 
10
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl-2.1.html
 
11
# - or any later version.
 
12
#
 
13
 
 
14
DEFAULT_OPENOFFICE_PORT = 8100
 
15
 
 
16
from os.path import abspath
 
17
from os.path import isfile
 
18
from os.path import splitext
 
19
import sys
 
20
from StringIO import StringIO
 
21
 
 
22
import uno
 
23
import unohelper
 
24
from com.sun.star.beans import PropertyValue
 
25
from com.sun.star.uno import Exception as UnoException
 
26
from com.sun.star.connection import NoConnectException
 
27
from com.sun.star.io import XOutputStream
 
28
from com.sun.star.io import IOException
 
29
 
 
30
class DocumentConversionException(Exception):
 
31
 
 
32
        def __init__(self, message):
 
33
                self.message = message
 
34
 
 
35
        def __str__(self):
 
36
                return self.message
 
37
 
 
38
class OutputStreamWrapper(unohelper.Base, XOutputStream):
 
39
    """ Minimal Implementation of XOutputStream """
 
40
    def __init__(self, debug=True):
 
41
        self.debug = debug
 
42
        self.data = StringIO()
 
43
        self.position = 0
 
44
        if self.debug:
 
45
            sys.stderr.write("__init__ OutputStreamWrapper.\n")
 
46
 
 
47
    def writeBytes(self, bytes):
 
48
        if self.debug:
 
49
            sys.stderr.write("writeBytes %i bytes.\n" % len(bytes.value))
 
50
        self.data.write(bytes.value)
 
51
        self.position += len(bytes.value)
 
52
 
 
53
    def close(self):
 
54
        if self.debug:
 
55
            sys.stderr.write("Closing output. %i bytes written.\n" % self.position)
 
56
        self.data.close()
 
57
 
 
58
    def flush(self):
 
59
        if self.debug:
 
60
            sys.stderr.write("Flushing output.\n")
 
61
        pass
 
62
    def closeOutput(self):
 
63
        if self.debug:
 
64
            sys.stderr.write("Closing output.\n")
 
65
        pass
 
66
 
 
67
class DocumentConverter:
 
68
    
 
69
    def __init__(self, host='localhost',port=DEFAULT_OPENOFFICE_PORT):
 
70
        self.localContext = uno.getComponentContext()
 
71
        self.serviceManager = self.localContext.ServiceManager
 
72
        resolver = self.serviceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", self.localContext)
 
73
        try:
 
74
            context = resolver.resolve("uno:socket,host=%s,port=%s;urp;StarOffice.ComponentContext" % (host, port))
 
75
        except NoConnectException, exception:
 
76
            raise DocumentConversionException, "Failed to connect to OpenOffice.org on port %s. %s" % (port, exception)
 
77
        self.desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
 
78
 
 
79
    def convertByStream(self, stdinBytes):
 
80
        inputStream = self.serviceManager.createInstanceWithContext("com.sun.star.io.SequenceInputStream", self.localContext)
 
81
        inputStream.initialize((uno.ByteSequence(stdinBytes),)) 
 
82
 
 
83
        document = self.desktop.loadComponentFromURL('private:stream', "_blank", 0, self._toProperties(
 
84
            InputStream = inputStream
 
85
            ))
 
86
 
 
87
        if not document:
 
88
            raise DocumentConversionException, "Error making document"
 
89
        try:
 
90
            document.refresh()
 
91
        except AttributeError, e:
 
92
            pass
 
93
        outputStream = OutputStreamWrapper(False)
 
94
        try:
 
95
            document.storeToURL('private:stream', self._toProperties(
 
96
                OutputStream = outputStream,
 
97
                FilterName = "writer_pdf_Export"))
 
98
        except IOException, e:
 
99
            print ("IOException during conversion: %s - %s" % (e.ErrCode, e.Message))       
 
100
 
 
101
        document.close(True)
 
102
        openDocumentBytes = outputStream.data.getvalue()
 
103
        outputStream.close()
 
104
        return openDocumentBytes
 
105
 
 
106
 
 
107
    def convertByPath(self, inputFile, outputFile):
 
108
        inputUrl = self._toFileUrl(inputFile)
 
109
        outputUrl = self._toFileUrl(outputFile)
 
110
        print inputUrl
 
111
        print outputUrl
 
112
        document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(Hidden=True))
 
113
        try:
 
114
            document.refresh()
 
115
        except AttributeError:
 
116
            pass
 
117
        try:
 
118
            document.storeToURL(outputUrl, self._toProperties(FilterName="writer_pdf_Export"))
 
119
        finally:
 
120
            document.close(True)
 
121
 
 
122
    def _toFileUrl(self, path):
 
123
        return uno.systemPathToFileUrl(abspath(path))
 
124
 
 
125
    def _toProperties(self, **args):
 
126
        props = []
 
127
        for key in args:
 
128
            prop = PropertyValue()
 
129
            prop.Name = key
 
130
            prop.Value = args[key]
 
131
            props.append(prop)
 
132
        return tuple(props)
 
133