Guest User

oo converter

a guest
Jul 28th, 2010
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.63 KB | None | 0 0
  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 <[email protected]>
  9. #                    Matthew Holloway <[email protected]>
  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 = 2002
  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.task import ErrorCodeIOException
  26. from com.sun.star.uno import Exception as UnoException
  27. from com.sun.star.connection import NoConnectException
  28. from com.sun.star.io import XOutputStream
  29.  
  30. class OutputStreamWrapper(unohelper.Base, XOutputStream):
  31.     """ Minimal Implementation of XOutputStream """
  32.     def __init__(self, debug=True):
  33.         self.debug = debug
  34.         self.data = StringIO()
  35.         self.position = 0
  36.         if self.debug:
  37.             sys.stderr.write("__init__ OutputStreamWrapper.\n")
  38.  
  39.     def writeBytes(self, bytes):
  40.         if self.debug:
  41.             sys.stderr.write("writeBytes %i bytes.\n" % len(bytes.value))
  42.         self.data.write(bytes.value)
  43.         self.position += len(bytes.value)
  44.  
  45.     def close(self):
  46.         if self.debug:
  47.             sys.stderr.write("Closing output. %i bytes written.\n" % self.position)
  48.         self.data.close()
  49.  
  50.     def flush(self):
  51.         if self.debug:
  52.             sys.stderr.write("Flushing output.\n")
  53.         pass
  54.  
  55.  
  56. class DocumentConverter:
  57.    
  58.     def __init__(self, port=DEFAULT_OPENOFFICE_PORT):
  59.         self.localContext = uno.getComponentContext()
  60.         self.serviceManager = self.localContext.ServiceManager
  61.         resolver = self.serviceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", self.localContext)
  62.         try:
  63.             context = resolver.resolve("uno:pipe,name=oood-1;urp;StarOffice.ComponentContext")
  64.         except NoConnectException, exception:
  65.             raise Exception, "Failed to connect to OpenOffice.org on port %s. %s" % (port, exception)
  66.         self.desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
  67.  
  68.     def convertByStream(self, stdinBytes):
  69.         inputStream = self.serviceManager.createInstanceWithContext("com.sun.star.io.SequenceInputStream", self.localContext)
  70.         inputStream.initialize((uno.ByteSequence(stdinBytes),))
  71.  
  72.         document = self.desktop.loadComponentFromURL('private:stream', "_blank", 0, self._toProperties(
  73.             InputStream=inputStream,
  74.                         FilterName='writer8',
  75.             ReadOnly=True))
  76.  
  77.         if not document:
  78.             raise Exception, "Error making document"
  79.         try:
  80.             document.refresh()
  81.         except AttributeError:
  82.             pass
  83.         outputStream = OutputStreamWrapper(False)
  84.         try:
  85.             document.storeToURL('private:stream', self._toProperties(
  86.                 OutputStream=outputStream,
  87.                 FilterName="writer_pdf_Export"))
  88.                 except Exception, e:
  89.             print >>sys.stderr, 'Error: %s' % str(e.ErrCode)
  90.                         raise
  91.         finally:
  92.             document.close(True)
  93.         openDocumentBytes = outputStream.data.getvalue()
  94.         outputStream.close()
  95.         return openDocumentBytes
  96.  
  97.  
  98.     def convertByPath(self, inputFile, outputFile):
  99.         inputUrl = self._toFileUrl(inputFile)
  100.         outputUrl = self._toFileUrl(outputFile)
  101.         document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(Hidden=True))
  102.         try:
  103.             document.refresh()
  104.         except AttributeError:
  105.             pass
  106.         try:
  107.             document.storeToURL(outputUrl, self._toProperties(FilterName="writer8"))
  108.         finally:
  109.             document.close(True)
  110.  
  111.     def _toFileUrl(self, path):
  112.         return uno.systemPathToFileUrl(abspath(path))
  113.  
  114.     def _toProperties(self, **args):
  115.         props = []
  116.         for key in args:
  117.             prop = PropertyValue()
  118.             prop.Name = key
  119.             prop.Value = args[key]
  120.             props.append(prop)
  121.         return tuple(props)
  122.  
  123. if __name__ == "__main__":
  124.     if len(sys.argv) == 2 and sys.argv[1] == '--stream':
  125.         stdinBytes = sys.stdin.read()
  126.         converter = DocumentConverter()
  127.         openDocumentBytes = converter.convertByStream(stdinBytes)
  128.         sys.stdout.write(openDocumentBytes)
  129.         sys.stderr.write("(Success)\n")
  130.         sys.exit(0)
  131.     elif len(sys.argv) == 3:
  132.         converter = DocumentConverter()
  133.         if not isfile(sys.argv[1]):
  134.             sys.stderr.write("No such input file: %s\n" % sys.argv[1])
  135.             sys.exit(255)
  136.         converter.convertByPath(sys.argv[1], sys.argv[2])
  137.     else:
  138.         helpText = "USAGE: " + sys.argv[0] + " <input-path> <output-path>\n"
  139.         helpText += "USAGE: " + sys.argv[0] + " --stream  (accepts binary document on stdin and outputs on stdout)\n"
  140.         sys.stderr.write(helpText)
  141.         sys.exit(255)
Advertisement
Add Comment
Please, Sign In to add comment