Пример #1
0
def convert(message):
    global nbConsecutiveAttemptOpeningDocument 
    ### Parse the message 
    messageSplit = shlex.split(message)
    fileOption = parser.parse_args(args=messageSplit)

    document = None
    inputprops = UnoProps(Hidden=True, ReadOnly=True, UpdateDocMode=QUIET_UPDATE)
    cwd = unohelper.systemPathToFileUrl( os.getcwd() )
    inputurl = unohelper.absolutize(cwd, unohelper.systemPathToFileUrl(fileOption.input))

    try:
        document = desktop.loadComponentFromURL( inputurl , "_blank", 0, inputprops)
    except:
        sendErrorOrExit('400')
        return

    if not document:
        sendErrorOrExit('400')
        return

    ### Reset counter
    nbConsecutiveAttemptOpeningDocument = 0

    ### Update document links (update sub-documents)
    try:
        document.updateLinks()
    except AttributeError:
        # the document doesn't implement the XLinkUpdate interface
        pass

    ### Update document indexes
    try:
        document.refresh()
        indexes = document.getDocumentIndexes()
    except AttributeError:
        # the document doesn't implement the XRefreshable and/or
        # XDocumentIndexesSupplier interfaces
        pass
    else:
        for i in range(0, indexes.getCount()):
            indexes.getByIndex(i).update()

    outputprops = UnoProps(FilterName=fileOption.format, Overwrite=True)
    if fileOption.formatOptions != '':
        outputprops += UnoProps(FilterOptions=fileOption.formatOptions)
    outputurl = unohelper.absolutize(cwd, unohelper.systemPathToFileUrl(fileOption.output) )

    try:
        document.storeToURL(outputurl, tuple(outputprops) )
    except:
        sendErrorOrExit('401') # could not convert document
        document.dispose()
        document.close(True)
        return

    document.dispose()
    document.close(True)
    send('200') ### Document converted
Пример #2
0
    def store(self, xMSF, xComponent, StorePath, FilterName):
        try:
            if len(FilterName):
                oStoreProperties = list(range(2))
                oStoreProperties[0] = uno.createUnoStruct(
                    'com.sun.star.beans.PropertyValue')
                oStoreProperties[0].Name = "FilterName"
                oStoreProperties[0].Value = FilterName
                oStoreProperties[1] = uno.createUnoStruct(
                    'com.sun.star.beans.PropertyValue')
                oStoreProperties[1].Name = "InteractionHandler"
                oStoreProperties[1].Value = xMSF.createInstance(
                    "com.sun.star.comp.uui.UUIInteractionHandler")
            else:
                oStoreProperties = list(range(0))

            StorePath = systemPathToFileUrl(StorePath)
            sPath = StorePath[:(StorePath.rfind("/") + 1)]
            sFile = StorePath[(StorePath.rfind("/") + 1):]
            xComponent.storeToURL(absolutize(sPath, sFile),
                                  tuple(oStoreProperties))
            return True
        except ErrorCodeIOException:
            #Throw this exception when trying to save a file
            #which is already opened in Libreoffice
            #TODO: handle it properly
            return True
            pass
        except Exception:
            traceback.print_exc()
            return False
Пример #3
0
    def store(self, xMSF, xComponent, StorePath, FilterName):
        try:
            if len(FilterName):
                oStoreProperties = list(range(2))
                oStoreProperties[0] = uno.createUnoStruct(
                    'com.sun.star.beans.PropertyValue')
                oStoreProperties[0].Name = "FilterName"
                oStoreProperties[0].Value = FilterName
                oStoreProperties[1] = uno.createUnoStruct(
                    'com.sun.star.beans.PropertyValue')
                oStoreProperties[1].Name = "InteractionHandler"
                oStoreProperties[1].Value = xMSF.createInstance(
                    "com.sun.star.comp.uui.UUIInteractionHandler")
            else:
                oStoreProperties = list(range(0))

            StorePath = systemPathToFileUrl(StorePath)
            sPath = StorePath[:(StorePath.rfind("/") + 1)]
            sFile = StorePath[(StorePath.rfind("/") + 1):]
            xComponent.storeToURL(
                absolutize(sPath, sFile), tuple(oStoreProperties))
            return True
        except ErrorCodeIOException:
            #Throw this exception when trying to save a file
            #which is already opened in Libreoffice
            #TODO: handle it properly
            return True
            pass
        except Exception:
            traceback.print_exc()
            return False
Пример #4
0
        def __init__(self, filename):
            """Create a reader"""
            local = uno.getComponentContext()
            resolver = local.ServiceManager.createInstanceWithContext(
                                "com.sun.star.bridge.UnoUrlResolver", local)

            try:
                context = resolver.resolve(
                    "uno:socket,host=localhost,port=2002;"
                    "urp;StarOffice.ComponentContext")
            except NoConnectException:
                raise Exception(CONNECT_MSG)

            desktop = context.ServiceManager.createInstanceWithContext(
                                        "com.sun.star.frame.Desktop", context)

            cwd = systemPathToFileUrl(os.getcwd())
            file_url = absolutize(cwd, systemPathToFileUrl(
                    os.path.join(os.getcwd(), filename)))
            in_props = PropertyValue("Hidden", 0, True, 0),
            document = desktop.loadComponentFromURL(
                file_url, "_blank", 0, in_props)
            self.rules = document.Sheets.getByName(u'rules')
            try:
                self.invalid = document.Sheets.getByName(u'invalid')
            except NoSuchElementException:
                self.invalid = None
Пример #5
0
	def initpath( self ):
		path = self.config.Origin
		expander = self.ctx.getValueByName( '/singletons/com.sun.star.util.theMacroExpander' )
		path = expander.expandMacros( path )
		path = path[len( 'vnd.sun.star.expand:' ):]
		import os
		path = unohelper.absolutize( os.getcwd(), path )
		path = unohelper.fileUrlToSystemPath( path )
		self.path = path
def load_file(desktop, path):
  cwd = systemPathToFileUrl(getcwd())
  file_url = absolutize(cwd, systemPathToFileUrl(path))
  sys.stderr.write(file_url + "\n")

  in_props = (
    #   PropertyValue("Hidden", 0 , True, 0),
    )
  return desktop.loadComponentFromURL(file_url, "_blank", 0, in_props)
Пример #7
0
 def initpath(self):
     path = self.config.Origin
     expander = self.ctx.getValueByName(
         '/singletons/com.sun.star.util.theMacroExpander')
     path = expander.expandMacros(path)
     path = path[len('vnd.sun.star.expand:'):]
     path = unohelper.absolutize(os.getcwd(), path)
     path = unohelper.fileUrlToSystemPath(path)
     self.path = path
Пример #8
0
def load_file(desktop, path):
    cwd = systemPathToFileUrl(getcwd())
    file_url = absolutize(cwd, systemPathToFileUrl(path))
    sys.stderr.write(file_url + "\n")

    in_props = (
        #   PropertyValue("Hidden", 0 , True, 0),
    )
    return desktop.loadComponentFromURL(file_url, "_blank", 0, in_props)
Пример #9
0
	def getpath( ctx, classname ):
		config = getconfig( ctx, 'org.openoffice.eoec.%sSettings/ConfigNode'%classname )
		path = config.Origin
		expander = ctx.getValueByName( '/singletons/com.sun.star.util.theMacroExpander' )
		path = expander.expandMacros( path )
		path = path[len( 'vnd.sun.star.expand:' ):]
		import os
		path = unohelper.absolutize( os.getcwd(), path )
		path = unohelper.fileUrlToSystemPath( path )
		return path
Пример #10
0
 def save_and_close( self, outputfile ):
     cwd = systemPathToFileUrl( getcwd() )
     args = ( makePropertyValue("FilterName","MS Word 97"), )
     destFile = absolutize( cwd, systemPathToFileUrl(outputfile) )
     self.doc.storeAsURL(destFile, args)
     try:
         self.doc.dispose()
     except:
         print "error while saving doc"
     return 1
Пример #11
0
    def testUrlHelper(self):
        systemPath = os.getcwd()
        if systemPath.startswith("/"):
            self.failUnless("/tmp" == unohelper.fileUrlToSystemPath("file:///tmp"))
            self.failUnless("file:///tmp" == unohelper.systemPathToFileUrl("/tmp"))
        else:
            self.failUnless("c:\\temp" == unohelper.fileUrlToSystemPath("file:///c:/temp"))
            self.failUnless("file:///c:/temp" == unohelper.systemPathToFileUrl("c:\\temp"))

        systemPath = unohelper.systemPathToFileUrl(systemPath)
        self.failUnless(systemPath + "/a" == unohelper.absolutize(systemPath, "a"))
Пример #12
0
      def testUrlHelper( self ):
            systemPath = os.getcwd()
            if systemPath.startswith( "/" ):
                  self.failUnless( "/tmp" == unohelper.fileUrlToSystemPath( "file:///tmp" ) )
                  self.failUnless( "file:///tmp" == unohelper.systemPathToFileUrl( "/tmp" ))
            else:
                  self.failUnless( "c:\\temp" == unohelper.fileUrlToSystemPath( "file:///c:/temp" ) )
                  self.failUnless( "file:///c:/temp" == unohelper.systemPathToFileUrl( "c:\\temp" ) )

            systemPath = unohelper.systemPathToFileUrl( systemPath )
            self.failUnless( systemPath + "/a" == unohelper.absolutize( systemPath, "a" ) )
Пример #13
0
    def _exportToPDF(self,pdfname):
        pdfUrl = absolutize(self._cwd, systemPathToFileUrl(pdfname) )
        filterProps=PropertyValue()
        filterProps.Name="FilterName"
        filterProps.Value="writer_pdf_Export"

        owProps=PropertyValue()
        owProps.Name="Overwrite"
        owProps.Value=True

        self._doc.storeToURL(pdfUrl,(filterProps,owProps))
def write_pdf(doc, path):
  out_props = (
    PropertyValue("FilterName", 0, "writer_pdf_Export", 0),
    PropertyValue("Overwrite", 0, True, 0),
    )

  (dest, ext) = splitext(path)
  dest = dest + ".pdf"
  dest_url = absolutize(systemPathToFileUrl(getcwd()), systemPathToFileUrl(dest))
  sys.stderr.write(dest_url + "\n")
  doc.storeToURL(dest_url, out_props)
  doc.dispose()
Пример #15
0
 def save_and_close(self, doc, outputfile):
     self.setup_locals(doc)
     cwd = systemPathToFileUrl(getcwd())
     args = (makePropertyValue("FilterName", "MS Word 97"), )
     destFile = absolutize(cwd, systemPathToFileUrl(outputfile))
     self.doc.storeAsURL(destFile, args)
     try:
         self.doc.dispose()
     except:
         print("error while saving doc")
     del self.docs[doc]
     return 1
Пример #16
0
def write_pdf(doc, path):
    out_props = (
        PropertyValue("FilterName", 0, "writer_pdf_Export", 0),
        PropertyValue("Overwrite", 0, True, 0),
    )

    (dest, ext) = splitext(path)
    dest = dest + ".pdf"
    dest_url = absolutize(systemPathToFileUrl(getcwd()),
                          systemPathToFileUrl(dest))
    sys.stderr.write(dest_url + "\n")
    doc.storeToURL(dest_url, out_props)
    doc.dispose()
Пример #17
0
    def getModuleFromUrl(self, url):
        if DEBUG:
            print("pythonloader: interpreting url " + url)
        protocol, dependent = splitUrl(url)
        if "vnd.sun.star.expand" == protocol:
            exp = self.ctx.getValueByName(
                "/singletons/com.sun.star.util.theMacroExpander")
            url = exp.expandMacros(dependent)
            protocol, dependent = splitUrl(url)

        if DEBUG:
            print("pythonloader: after expansion " + protocol + ":" +
                  dependent)

        try:
            if "file" == protocol:
                # remove \..\ sequence, which may be useful e.g. in the build env
                url = unohelper.absolutize(url, url)

                # did we load the module already ?
                mod = g_loadedComponents.get(url)
                if not mod:
                    mod = imp.new_module("uno_component")

                    # check for pythonpath.zip beside .py files
                    checkForPythonPathBesideComponent(url[0:url.rfind('/')])

                    # read the file
                    filename = unohelper.fileUrlToSystemPath(url)
                    fileHandle = file(filename)
                    src = fileHandle.read().replace("\r", "")
                    if not src.endswith("\n"):
                        src = src + "\n"

                    # compile and execute the module
                    codeobject = compile(src, encfile(filename), "exec")
                    exec(codeobject, mod.__dict__)
                    mod.__file__ = encfile(filename)
                    g_loadedComponents[url] = mod
                return mod
            elif "vnd.openoffice.pymodule" == protocol:
                return __import__(dependent)
            else:
                raise RuntimeException(
                    "PythonLoader: Unknown protocol " + protocol + " in url " +
                    url, self)
        except ImportError as e:
            raise RuntimeException(
                "Couldn't load " + url + " for reason " + str(e), None)
        return None
Пример #18
0
def convert(message):
    global nbConsecutiveAttemptOpeningDocument 
    ### Parse the message 
    messageSplit = shlex.split(message)
    fileOption = parser.parse_args(args=messageSplit)

    document = None
    inputprops = UnoProps(Hidden=True, ReadOnly=True, UpdateDocMode=QUIET_UPDATE)
    cwd = unohelper.systemPathToFileUrl( os.getcwd() )
    inputurl = unohelper.absolutize(cwd, unohelper.systemPathToFileUrl(fileOption.input))

    try:
        document = desktop.loadComponentFromURL( inputurl , "_blank", 0, inputprops)
    except:
        sendErrorOrExit('400')
        return
Пример #19
0
    def getModuleFromUrl( self, url ):
        if DEBUG:
            print("pythonloader: interpreting url " +url)
        protocol, dependent = splitUrl( url )
        if "vnd.sun.star.expand" == protocol:
            exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" )
            url = exp.expandMacros(dependent)
            protocol,dependent = splitUrl( url )

        if DEBUG:
            print("pythonloader: after expansion " +protocol +":" + dependent)

        try:
            if "file" == protocol:
                # remove \..\ sequence, which may be useful e.g. in the build env
                url = unohelper.absolutize( url, url )

                # did we load the module already ?
                mod = g_loadedComponents.get( url )
                if not mod:
                    mod = imp.new_module("uno_component")

                    # check for pythonpath.zip beside .py files
                    checkForPythonPathBesideComponent( url[0:url.rfind('/')] )

                    # read the file
                    filename = unohelper.fileUrlToSystemPath( url )
                    fileHandle = file( filename )
                    src = fileHandle.read().replace("\r","")
                    if not src.endswith( "\n" ):
                        src = src + "\n"

                    # compile and execute the module
                    codeobject = compile( src, encfile(filename), "exec" )
                    exec(codeobject, mod.__dict__)
                    mod.__file__ = encfile(filename)
                    g_loadedComponents[url] = mod
                return mod
            elif "vnd.openoffice.pymodule" == protocol:
                return  __import__( dependent )
            else:
                raise RuntimeException( "PythonLoader: Unknown protocol " +
                                        protocol + " in url " +url, self )
        except ImportError as e:
            raise RuntimeException( "Couldn't load "+url+ " for reason "+str(e), None)
        return None
Пример #20
0
    def convert(self, inputfn):
        """
        This method takes a LibreOffice document as a byte object as parameter and returns the
        associated pdf file as a byte object.
        """
        document = None

        # Load inputfile
        inputprops = uno_props(Hidden=True, ReadOnly=True, UpdateDocMode=QUIET_UPDATE)

        if isinstance(inputfn, bytes):
            inputStream = self.svcmgr.createInstanceWithContext(
                "com.sun.star.io.SequenceInputStream", self.context)
            inputStream.initialize((uno.ByteSequence(inputfn),))
            inputprops += uno_props(InputStream=inputStream)
            inputurl = 'private:stream'
        else:
            inputfn_type = type(inputfn)
            logger.error('Incorrect type for the input parameter: %s unrecognized' % inputfn_type)
            sys.exit(2)

        document = self.desktop.loadComponentFromURL(inputurl, "_blank", 0, inputprops)
        if not document:
            logger.error('Could not open the document.')
            sys.exit(2)

        outputprops = uno_props(FilterName='writer_pdf_Export', Overwrite=True)

        outputf = NamedTemporaryFile()
        outputurl = unohelper.absolutize(gettempdir(), unohelper.systemPathToFileUrl(outputf.name))

        document.storeToURL(outputurl, outputprops)
        document.dispose()
        document.close(True)

        with open(outputf.name, 'rb') as read_file:
            pdf_content = read_file.read()
        if not pdf_content:
            logger.error('soffice error please check.')
            sys.exit(2)
        return pdf_content
Пример #21
0
def main():
        """Main.
        """
        uri_tmpl = "uno:%s;urp;StarOffice.ComponentContext"
        constr = 'socket,host=localhost,port=2002'

        uri = uri_tmpl % (constr)

        try:
                opts, args = getopt.getopt(sys.argv[1:], "hc:", ["help", "connection="])
                for o, a in opts:
                        if o in ("-h", "--help"):
                                usage(0)
                        if o in ("-c", "--connection"):
                                uri = uri_tmpl % (a,)
        except getopt.GetoptError:
                usage(1)
        
        if len(args) < 2:
                usage(1, True)

        (src, dst) = args[:2]

        filter = findFilter(src, dst)
        if not filter:
                raise "No suitable filter found. Aborting..."
                sys.exit(1)

        cwd = unohelper.systemPathToFileUrl(os.getcwd())
        p2u = lambda path: unohelper.absolutize(cwd, unohelper.systemPathToFileUrl(path))

        try:
                desktop = initDesktop(uri)
                convert(desktop, p2u(src), p2u(dst), filter)

        except com.sun.star.connection.NoConnectException, e:
                print >> sys.stderr, e.Message
                warnOOoNotRunning()
                sys.exit(1)
Пример #22
0
def main():
    retVal = 0
    doc = None
    stdout = False

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:",
            ["help", "connection-string=" , "html", "pdf", "stdout" ])
        url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
        filterName = "Text (Encoded)"
        extension  = "txt"
        for o, a in opts:
            if o in ("-h", "--help"):
                usage()
                sys.exit()
            if o in ("-c", "--connection-string" ):
                url = "uno:" + a + ";urp;StarOffice.ComponentContext"
            if o == "--html":
                filterName = "HTML (StarWriter)"
                extension  = "html"
            if o == "--pdf":
                filterName = "writer_pdf_Export"
                extension  = "pdf"
	    if o == "--stdout":
	    	stdout = True
                
        if not len( args ):
            usage()
            sys.exit()
              
        ctxLocal = uno.getComponentContext()
        smgrLocal = ctxLocal.ServiceManager

        resolver = smgrLocal.createInstanceWithContext(
                 "com.sun.star.bridge.UnoUrlResolver", ctxLocal )
        ctx = resolver.resolve( url )
        smgr = ctx.ServiceManager

        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx )

        cwd = systemPathToFileUrl( getcwd() )
        outProps = (
            PropertyValue( "FilterName" , 0, filterName , 0 ),
	    PropertyValue( "Overwrite" , 0, True , 0 ),
            PropertyValue( "OutputStream", 0, OutputStream(), 0)
	)
	    
        inProps = PropertyValue( "Hidden" , 0 , True, 0 ),
        for path in args:
            try:
                fileUrl = absolutize( cwd, systemPathToFileUrl(path) )
                doc = desktop.loadComponentFromURL( fileUrl , "_blank", 0, inProps )


		#Get list structures 
		c =  doc.NumberingRules.Count
		lists = dict()
		for ruleNum in range(0 , c ):
			
			numberingRule = doc.NumberingRules.getByIndex(ruleNum)
			listId = numberingRule.DefaultListId
			lists[listId] = []
			for i in range(0,numberingRule.Count):
				lists[listId].append(dict())
				
				rule = numberingRule.getByIndex(i)
				for prop in rule:
					lists[listId][i][prop.Name] = prop.Value

		#print lists
		
		curs = doc.Text.createTextCursor()
		while curs.gotoNextParagraph(False): 
			print "Paragraph:"
			left = curs.ParaLeftMargin
			lid = curs.ListId
			if lid <> "":
				print lid
				#print dir(curs)
				level = curs.OutlineLevel
				print "Level %s" % str(level)
				left = lists[lid][level]["IndentAt"]
				#print lists[lid][level]
			print "LeftMargin %s" % str(left)
			bookmark = doc.createInstance("com.sun.star.text.Bookmark")
			bookmark.setName("left-margin:%s-" % str(left))
			doc.Text.insertTextContent(curs,bookmark,False)
 			#print dir(bookmark)

			
		print dir(doc.Text)

	


                if not doc:
                    raise UnoException( "Couldn't open stream for unknown reason", None )

		if not stdout:
                    (dest, ext) = splitext(path)
                    dest = dest + "." + extension
                    destUrl = absolutize( cwd, systemPathToFileUrl(dest) )
                    sys.stderr.write(destUrl + "\n")
                    doc.storeToURL(destUrl, outProps)
		else:
		    doc.storeToURL("private:stream",outProps)
            except IOException, e:
                sys.stderr.write( "Error during conversion: " + e.Message + "\n" )
                retVal = 1
            except UnoException, e:
                sys.stderr.write( "Error ("+repr(e.__class__)+") during conversion:" + e.Message + "\n" )
                retVal = 1
Пример #23
0
        resolver = smgrLocal.createInstanceWithContext(
                   "com.sun.star.bridge.UnoUrlResolver", ctxLocal )
        ctx = resolver.resolve( url )
        smgr = ctx.ServiceManager
        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx )
    except NoConnectException, e:
        sys.stderr.write("OpenOffice process not found or not listening (" + e.Message + ")\n")
        sys.exit(1)
    except IllegalArgumentException, e:
        sys.stderr.write("The url is invalid ( " + e.Message + ")\n")
        sys.exit(1)
    except RuntimeException, e:
        sys.stderr.write("An unknown error occured: " + e.Message + "\n")

    cwd = systemPathToFileUrl( getcwd() )
    destFile = absolutize( cwd, systemPathToFileUrl(outputfile) )
    inProps = PropertyValue( "Hidden" , 0 , True, 0 ),

    newdoc = desktop.loadComponentFromURL( "private:factory/swriter", "_blank", 0, inProps )
    text   = newdoc.Text
    cursor = text.createTextCursor()

    for i in args:
        if isfile(os.path.join(getcwd(), i)):
            try:
                fileUrl = absolutize( cwd, systemPathToFileUrl(i) )

                print "Appending %s" % fileUrl
                try:
                    cursor.gotoEnd(False)
                    cursor.BreakType = PAGE_BEFORE
Пример #24
0
    def getModuleFromUrl( self, url ):
        if DEBUG:
            print("pythonloader: interpreting url " + url)
        protocol, dependent = splitUrl( url )
        if "vnd.sun.star.expand" == protocol:
            exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" )
            url = exp.expandMacros(dependent)
            protocol,dependent = splitUrl( url )

        if DEBUG:
            print("pythonloader: after expansion " + protocol + ":" + dependent)

        try:
            if "file" == protocol:
                # remove \..\ sequence, which may be useful e.g. in the build env
                url = unohelper.absolutize( url, url )

                # did we load the module already ?
                mod = g_loadedComponents.get( url )
                if not mod:
                    mod = imp.new_module("uno_component")

                    # check for pythonpath.zip beside .py files
                    checkForPythonPathBesideComponent( url[0:url.rfind('/')] )

                    # read the file
                    filename = unohelper.fileUrlToSystemPath( url )

                    if sys.version >= '3':
                        fileHandle = open( filename, encoding='utf_8' )
                    else:
                        fileHandle = open( filename )
                    src = fileHandle.read().replace("\r","")
                    if not src.endswith( "\n" ):
                        src = src + "\n"

                    # compile and execute the module
                    codeobject = compile( src, encfile(filename), "exec" )
                    exec(codeobject, mod.__dict__)
                    mod.__file__ = encfile(filename)
                    g_loadedComponents[url] = mod
                return mod
            elif "vnd.openoffice.pymodule" == protocol:
                nSlash = dependent.rfind('/')
                if -1 != nSlash:
                    path = unohelper.fileUrlToSystemPath( dependent[0:nSlash] )
                    dependent = dependent[nSlash+1:len(dependent)]
                    if not path in sys.path:
                        sys.path.append( path )
                mod =  __import__( dependent )
                path_component, dot, rest = dependent.partition('.')
                while dot == '.':
                    path_component, dot, rest = rest.partition('.')
                    mod = getattr(mod, path_component)
                return mod
            else:
                if DEBUG:
                    print("Unknown protocol '" + protocol + "'");
                raise RuntimeException( "PythonLoader: Unknown protocol " +
                                         protocol + " in url " +url, self )
        except Exception as e:
            if DEBUG:
                print ("Python import exception " + str(type(e)) +
                       " message " + str(e) + " args " + str(e.args));
            raise RuntimeException( "Couldn't load " + url + " for reason " + str(e), None )
        return None
Пример #25
0
    def convert(self, inputfn):
        global exitcode

        doc = None
        outputfmt = self.getformat(inputfn)

        if op.verbose > 0:
            print >>sys.stderr, 'Input file:', inputfn

        if not os.path.exists(inputfn):
            print >>sys.stderr, 'unoconv: file `%s\' does not exist.' % inputfn
            exitcode = 1

        try:
            ### Load inputfile
            inputprops = ( PropertyValue( "Hidden", 0, True, 0 ), )

            inputurl = unohelper.absolutize(self.cwd, unohelper.systemPathToFileUrl(inputfn))
            doc = self.desktop.loadComponentFromURL( inputurl , "_blank", 0, inputprops )

            if not doc:
                raise UnoException("File could not be loaded by OpenOffice", None)

#            standard = doc.getStyleFamilies().getByName('PageStyles').getByName('Standard')
#            pageSize = Size()
#            pageSize.Width=1480
#            pageSize.Height=3354
#            standard.setPropertyValue('Size', pageSize)

            error(1, "Selected output format: %s" % outputfmt)
            # pylint: disable=E1103
            # outputfmt is an instance of the class Fmt.
            error(1, "Selected ooffice filter: %s" % outputfmt.filter)
            error(1, "Used doctype: %s" % outputfmt.doctype)

####            ### Write outputfile
####            outputprops = (
####                    PropertyValue( "FilterName", 0, outputfmt.filter, 0),
####                    PropertyValue( "Overwrite", 0, True, 0 ),
#####                    PropertyValue( "Size", 0, "A3", 0 ),
####                    PropertyValue( "OutputStream", 0, OutputStream(), 0 ),
####                   )

            ### BEG Invenio customizations
            outputprops = [
                    PropertyValue( "FilterName" , 0, outputfmt.filter , 0 ),
                    PropertyValue( "Overwrite" , 0, True , 0 ),
                    PropertyValue( "OutputStream", 0, OutputStream(), 0),
                   ]
            if outputfmt.filter == 'Text (encoded)':
                ## To enable UTF-8
                outputprops.append(PropertyValue( "FilterFlags", 0, "UTF8, LF", 0))
            elif outputfmt.filter == 'writer_pdf_Export':
                ## To enable PDF/A
                outputprops.append(PropertyValue( "SelectPdfVersion", 0, 1, 0))

            outputprops = tuple(outputprops)
            ### END Invenio customizations

            if not op.stdout:
                (outputfn, ext) = os.path.splitext(inputfn)
                ### BEG Invenio customizations
                if op.outputfile:
                    outputfn = op.outputfile
                elif not op.outputpath: ### END Invenio customizations
                    outputfn = outputfn + '.' + outputfmt.extension
                else:
                    outputfn = os.path.join(op.outputpath, os.path.basename(outputfn) + '.' + outputfmt.extension)
                outputurl = unohelper.absolutize( self.cwd, unohelper.systemPathToFileUrl(outputfn) )
                doc.storeToURL(outputurl, outputprops)
                error(1, "Output file: %s" % outputfn)
            else:
                doc.storeToURL("private:stream", outputprops)

            # pylint: enable=E1103

            doc.dispose()
            doc.close(True)

        except SystemError, e:
            error(0, "unoconv: SystemError during conversion: %s" % e)
            error(0, "ERROR: The provided document cannot be converted to the desired format.")
            exitcode = 1
Пример #26
0
def main():
    retVal = 0
    doc = None
    stdout = False

    try:
        opts, args = getopt.getopt(
            sys.argv[1:], "hc:",
            ["help", "connection-string=", "html", "pdf", "stdout", "format="])
        url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
        filterName = "Text (Encoded)"
        extension = "txt"
        for o, a in opts:
            if o in ("-h", "--help"):
                usage()
                sys.exit()
            if o in ("-c", "--connection-string"):
                url = "uno:" + a + ";urp;StarOffice.ComponentContext"
            if o == "--html":
                filterName = "HTML (StarWriter)"
                extension = "html"
            if o == "--pdf":
                filterName = "writer_pdf_Export"
                extension = "pdf"
            if o in ("--format"):
                if a == "xls":
                    filterName = "HTML (StarCalc)"
                if a == "doc":
                    filterName = "HTML (StarWriter)"
            if o == "--stdout":
                stdout = True

        if not len(args):
            usage()
            sys.exit()

        ctxLocal = uno.getComponentContext()
        smgrLocal = ctxLocal.ServiceManager

        resolver = smgrLocal.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", ctxLocal)
        ctx = resolver.resolve(url)
        smgr = ctx.ServiceManager

        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",
                                                 ctx)

        cwd = systemPathToFileUrl(getcwd())
        outProps = (PropertyValue("FilterName", 0, filterName,
                                  0), PropertyValue("Overwrite", 0, True, 0),
                    PropertyValue("OutputStream", 0, OutputStream(), 0))

        inProps = PropertyValue("Hidden", 0, True, 0),
        for path in args:
            try:
                fileUrl = absolutize(cwd, systemPathToFileUrl(path))
                doc = desktop.loadComponentFromURL(fileUrl, "_blank", 0,
                                                   inProps)

                if not doc:
                    raise UnoException(
                        "Couldn't open stream for unknown reason", None)

                if not stdout:
                    (dest, ext) = splitext(path)
                    dest = dest + "." + extension
                    destUrl = absolutize(cwd, systemPathToFileUrl(dest))
                    sys.stderr.write(destUrl + "\n")
                    doc.storeToURL(destUrl, outProps)
                else:
                    doc.storeToURL("private:stream", outProps)
            except IOException, e:
                sys.stderr.write("Error during conversion: " + e.Message +
                                 "\n")
                retVal = 1
            except UnoException, e:
                sys.stderr.write("Error (" + repr(e.__class__) +
                                 ") during conversion:" + e.Message + "\n")
                retVal = 1
Пример #27
0
    def convert(self, inputfn, target_format, conversion_options=None):
        document = None

        self.log.debug('Input file: %s', inputfn)

        if not os.path.exists(inputfn):
            self.log.error('unoconv: file `%s\' does not exist.' % inputfn)
            return None

        try:
            ### Import phase
            phase = "import"

            ### Load inputfile
            input_md = UnoProps(Hidden=True, ReadOnly=True,
                                UpdateDocMode=QUIET_UPDATE)
            inputurl = unohelper.absolutize(self.cwd,
                                            unohelper.systemPathToFileUrl(
                                                inputfn))
            document = self.desktop.loadComponentFromURL(inputurl, "_blank", 0,
                                                         input_md)

            if not document:
                raise UnoException(
                    "The document '%s' could not be opened." % inputurl, None)

            ### Export phase
            phase = "export"

            (outputfn, ext) = os.path.splitext(inputfn)
            export_filter, out_exten = get_filter(ext, target_format)

            outputprops = UnoProps(FilterName=export_filter,
                                   OutputStream=OutputStream(),
                                   Overwrite=True)

            ### Set default filter options
            if conversion_options:
                filter_data = UnoProps(**conversion_options)
                outputprops += ( PropertyValue("FilterData",
                                               0,
                                               uno.Any(
                                                   "[]com.sun.star.beans.PropertyValue",
                                                   tuple(filter_data), ), 0), )

            outputfn = outputfn + os.extsep + out_exten

            outputurl = unohelper.absolutize(self.cwd,
                                             unohelper.systemPathToFileUrl(
                                                 outputfn))
            self.log.debug("Output file: %s" % outputfn)

            try:
                document.storeToURL(outputurl, tuple(outputprops))
            except IOException as e:
                raise UnoException(
                    "Unable to store document to %s (ErrCode %d)\n\nProperties: %s" % (
                    outputurl, e.ErrCode, outputprops), None)

            phase = "dispose"
            document.dispose()
            document.close(True)
            exitcode = 0
            return outputfn
        except SystemError as e:
            self.log.fatal(
                "unoconv: SystemError during %s phase:\n%s" % (phase, e))
            exitcode = 1

        except RuntimeException as e:
            self.log.fatal(
                "unoconv: RuntimeException during %s phase:\nOffice probably died. %s" % (
                phase, e))
            exitcode = 6

        except DisposedException as e:
            self.log.fatal(
                "unoconv: DisposedException during %s phase:\nOffice probably died. %s" % (
                phase, e))
            exitcode = 7

        except IllegalArgumentException as e:
            self.log.fatal(
                "UNO IllegalArgument during %s phase:\nSource file cannot be read. %s" % (
                phase, e))
            exitcode = 8

        except IOException as e:
        #            for attr in dir(e): print '%s: %s', (attr, getattr(e, attr))
            self.log.fatal("unoconv: IOException during %s phase:\n%s" % (
            phase, e.Message))
            exitcode = 3

        except CannotConvertException as e:
        #            for attr in dir(e): print '%s: %s', (attr, getattr(e, attr))
            self.log.fatal(
                "unoconv: CannotConvertException during %s phase:\n%s" % (
                phase, e.Message))
            exitcode = 4

        except UnoException as e:
            if hasattr(e, 'ErrCode'):
                self.log.fatal(
                    "unoconv: UnoException during %s phase in %s (ErrCode %d)" % (
                    phase, repr(e.__class__), e.ErrCode))
                exitcode = e.ErrCode
                pass
            if hasattr(e, 'Message'):
                self.log.fatal("unoconv: UnoException during %s phase:\n%s" % (
                phase, e.Message))
                exitcode = 5
            else:
                self.log.fatal("unoconv: UnoException during %s phase in %s" % (
                phase, repr(e.__class__)))
                exitcode = 2
                pass

        return exitcode
Пример #28
0
    print 'soffice "-accept=socket,host=localhost,port=2002;urp;"'
    print ""
    print "python d123.py D3.2.1-FINAL-v1.0.odt >../autobwam.py"
    sys.exit(1)

# Insert things into openoffice spreadsheet
compctx = uno.getComponentContext()
resolver = compctx.ServiceManager.createInstanceWithContext(UNORES,compctx)
ctx=resolver.resolve(UNORESID)
smgr=ctx.ServiceManager
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
model = desktop.getCurrentComponent()


cwd = unohelper.systemPathToFileUrl( os.getcwd() )
fileUrl = unohelper.absolutize( cwd, unohelper.systemPathToFileUrl(file) )

doc = desktop.loadComponentFromURL(fileUrl,"_blank",0,())
parser=bwamparser.BwamParser()

print """#! /usr/bin/env python
# -*- coding: utf-8 -*-
\"\"\"
NOTE autobwam.py is automatically generated. Do not edit this file by hand!

To regenerate the file, run:

cd $EIAOHOME/robacc/WAMs/wamlib/bwamparser
python d123.py D3.2.1-FINAL-v1.0.odt > ../autobwam.py

autobwam.py implements all B-WAM rules except two in D3.2.1 automatically.
Пример #29
0
    def getPDFFromOfficeDocument(self):
        #print 'in getPDFFROMofficeDocument before calling generic storePath'
        if self.getConversionState() == 'CANCELLED':
            return ''
        storePath = self.getGenericStorePath()
        #print storePath+'in getPDFFROMofficeDocument'
        infile = self.location
        #print infile
        local = uno.getComponentContext()
        resolver = local.ServiceManager.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", local)
        resolveUrl = "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext"
        context = resolver.resolve(resolveUrl)
        try:
            desktopService = context.ServiceManager.createInstance(
                "com.sun.star.frame.Desktop")
        #  print 'desktop service done'
        except:
            cherrypy.log('Error in getting desktop service... meeting ID = ' +
                         self.meetingID + ' and docID = ' + self.docID)
            self.setErrorCode(7909)
            return ''

        if self.getConversionState() == 'CANCELLED':
            return ''

        if sys.platform.startswith('win'):
            outfile = storePath + 'conv.pdf'
        else:
            outfile = storePath + '/conv.pdf'

        outtempFile = storePath + '\\conv.ps'

        args = (PropertyValue("Hidden", 0, True, 0), )
        url = unohelper.systemPathToFileUrl(self.location)
        try:
            sourceFile = desktopService.loadComponentFromURL(
                url, "_blank", 0, args)
            #print sourceFile
            #iPageCount = sourceFile.getDrawPages().getCount()
            #self.totalPageCount = iPageCount
            #print self.totalPageCount
        except:
            cherrypy.log(
                'Error has occured in loadComponentFromURL... meeting ID = ' +
                self.meetingID + ' and docID = ' + self.docID)
            self.setErrorCode(7406)
            return ''

        if self.getConversionState() == 'CANCELLED':
            return ''

        filterName = PropertyValue()
        filterName.Name = 'FilterName'
        filterName.Value = 'impress_pdf_Export'
        storePath = self.getGenericStorePath()
        pdfPath = unohelper.systemPathToFileUrl(storePath) + 'conv.pdf'
        #print pdfPath + ' in systemPathToFileUrl'
        urlData = PropertyValue()
        urlData.Name = 'URL'
        urlData.Value = pdfPath
        #print pdfPath
        try:
            sourceFile.storeToURL(
                unohelper.absolutize(
                    unohelper.systemPathToFileUrl(self.getGenericStorePath()),
                    unohelper.systemPathToFileUrl('conv.pdf')), (filterName, ))
#sourceFile.storeToURL(pdfPath, (filterName,))
        except:
            cherrypy.log(
                'Error in exporting document to PDF... meeting ID = ' +
                self.meetingID + ' and docID = ' + self.docID)
            self.setErrorCode(7407)
            storePath = ''

        if self.getConversionState() == 'CANCELLED':
            return ''

        try:
            sourceFile.dispose()
        except:
            cherrypy.log('Error in disposing document... meeting ID = ' +
                         self.meetingID + ' and docID = ' + self.docID)
            pass

        return storePath
Пример #30
0
    def convert(self, inputfn):
        global exitcode

        document = None
        outputfmt = self.getformat(inputfn)

        if op.verbose > 0:
            print >>sys.stderr, 'Input file:', inputfn

        if not os.path.exists(inputfn):
            print >>sys.stderr, 'unoconv: file `%s\' does not exist.' % inputfn
            exitcode = 1

        try:
            ### Load inputfile
            inputprops = (
                PropertyValue( "Hidden", 0, True, 0 ),
                PropertyValue( "ReadOnly", 0, True, 0 ),
                PropertyValue( "FilterOptions", 0, op.importfilter, 0 ),
            )

            inputurl = unohelper.absolutize(self.cwd, unohelper.systemPathToFileUrl(inputfn))
            document = self.desktop.loadComponentFromURL( inputurl , "_blank", 0, inputprops )

            if not document:
                raise UnoException("File could not be loaded by OpenOffice", None)

            ### Import style template
            if op.template:
                if os.path.exists(op.template):
                    if op.verbose > 0:
                        print >>sys.stderr, 'Template file:', op.template
                    templateprops = (
                        PropertyValue( "OverwriteStyles", 0, True, 0),
                    )
                    templateurl = unohelper.absolutize(self.cwd, unohelper.systemPathToFileUrl(op.template))
                    document.StyleFamilies.loadStylesFromURL(templateurl, templateprops)
                else:
                    print >>sys.stderr, 'unoconv: template file `%s\' does not exist.' % op.template
                    exitcode = 1

            info(1, "Selected output format: %s" % outputfmt)
            info(1, "Selected ooffice filter: %s" % outputfmt.filter)
            info(1, "Used doctype: %s" % outputfmt.doctype)

            ### Update document links
            try:
                document.updateLinks()
            except AttributeError:
                # the document doesn't implement the XLinkUpdate interface
                pass

            ### Update document indexes
            try:
                document.refresh()
                indexes = document.getDocumentIndexes()
            except AttributeError:
                # the document doesn't implement the XRefreshable and/or
                # XDocumentIndexesSupplier interfaces
                pass
            else:
                for i in range(0, indexes.getCount()):
                    indexes.getByIndex(i).update()

            ### Write outputfile
            outputprops = [
#                PropertyValue( "FilterData" , 0, ( PropertyValue( "SelectPdfVersion" , 0, 1 , uno.getConstantByName( "com.sun.star.beans.PropertyState.DIRECT_VALUE" ) ) ), uno.getConstantByName( "com.sun.star.beans.PropertyState.DIRECT_VALUE" ) ),
                PropertyValue( "FilterData", 0, uno.Any("[]com.sun.star.beans.PropertyValue", tuple( op.exportfilter ), ), 0 ),
                PropertyValue( "FilterName", 0, outputfmt.filter, 0),
#                PropertyValue( "SelectionOnly", 0, True, 0 ),
                PropertyValue( "OutputStream", 0, OutputStream(), 0 ),
                PropertyValue( "Overwrite", 0, True, 0 ),
            ]

            if outputfmt.filter == 'Text (encoded)':
                outputprops.append(PropertyValue( "FilterFlags", 0, "UTF8, LF", 0))
            ### BEG Invenio customizations
            elif outputfmt.filter == 'writer_pdf_Export':
                ## To enable PDF/A
                outputprops.append(PropertyValue( "SelectPdfVersion", 0, 1, 0))
            ### END Invenio customizations

            if not op.stdout:
                (outputfn, ext) = os.path.splitext(inputfn)
                if not op.output:
                    outputfn = outputfn + os.extsep + outputfmt.extension
                elif os.path.isdir(op.output):
                    outputfn = os.path.join(op.output, os.path.basename(outputfn) + os.extsep + outputfmt.extension)
                elif len(op.filenames) > 1:
                    outputfn = op.output + os.extsep + outputfmt.extension
                else:
                    outputfn = op.output

                outputurl = unohelper.absolutize( self.cwd, unohelper.systemPathToFileUrl(outputfn) )
                document.storeToURL(outputurl, tuple(outputprops) )
                info(1, "Output file: %s" % outputfn)
            else:
                document.storeToURL("private:stream", tuple(outputprops) )

            document.dispose()
            document.close(True)

        except SystemError, e:
            error("unoconv: SystemError during conversion: %s" % e)
            error("ERROR: The provided document cannot be converted to the desired format.")
            exitcode = 1
Пример #31
0
    def convert(self, inputfn, target_format, conversion_options=None):
        document = None

        self.log.debug('Input file: %s', inputfn)

        if not os.path.exists(inputfn):
            self.log.error('unoconv: file `%s\' does not exist.' % inputfn)
            return None

        try:
            ### Import phase
            phase = "import"

            ### Load inputfile
            input_md = UnoProps(Hidden=True,
                                ReadOnly=True,
                                UpdateDocMode=QUIET_UPDATE)
            inputurl = unohelper.absolutize(
                self.cwd, unohelper.systemPathToFileUrl(inputfn))
            document = self.desktop.loadComponentFromURL(
                inputurl, "_blank", 0, input_md)

            if not document:
                raise UnoException(
                    "The document '%s' could not be opened." % inputurl, None)

            ### Export phase
            phase = "export"

            (outputfn, ext) = os.path.splitext(inputfn)
            export_filter, out_exten = get_filter(ext, target_format)

            outputprops = UnoProps(FilterName=export_filter,
                                   OutputStream=OutputStream(),
                                   Overwrite=True)

            ### Set default filter options
            if conversion_options:
                filter_data = UnoProps(**conversion_options)
                outputprops += (PropertyValue(
                    "FilterData", 0,
                    uno.Any(
                        "[]com.sun.star.beans.PropertyValue",
                        tuple(filter_data),
                    ), 0), )

            outputfn = outputfn + os.extsep + out_exten

            outputurl = unohelper.absolutize(
                self.cwd, unohelper.systemPathToFileUrl(outputfn))
            self.log.debug("Output file: %s" % outputfn)

            try:
                document.storeToURL(outputurl, tuple(outputprops))
            except IOException as e:
                raise UnoException(
                    "Unable to store document to %s (ErrCode %d)\n\nProperties: %s"
                    % (outputurl, e.ErrCode, outputprops), None)

            phase = "dispose"
            document.dispose()
            document.close(True)
            exitcode = 0
            return outputfn
        except SystemError as e:
            self.log.fatal("unoconv: SystemError during %s phase:\n%s" %
                           (phase, e))
            exitcode = 1

        except RuntimeException as e:
            self.log.fatal(
                "unoconv: RuntimeException during %s phase:\nOffice probably died. %s"
                % (phase, e))
            exitcode = 6

        except DisposedException as e:
            self.log.fatal(
                "unoconv: DisposedException during %s phase:\nOffice probably died. %s"
                % (phase, e))
            exitcode = 7

        except IllegalArgumentException as e:
            self.log.fatal(
                "UNO IllegalArgument during %s phase:\nSource file cannot be read. %s"
                % (phase, e))
            exitcode = 8

        except IOException as e:
            #            for attr in dir(e): print '%s: %s', (attr, getattr(e, attr))
            self.log.fatal("unoconv: IOException during %s phase:\n%s" %
                           (phase, e.Message))
            exitcode = 3

        except CannotConvertException as e:
            #            for attr in dir(e): print '%s: %s', (attr, getattr(e, attr))
            self.log.fatal(
                "unoconv: CannotConvertException during %s phase:\n%s" %
                (phase, e.Message))
            exitcode = 4

        except UnoException as e:
            if hasattr(e, 'ErrCode'):
                self.log.fatal(
                    "unoconv: UnoException during %s phase in %s (ErrCode %d)"
                    % (phase, repr(e.__class__), e.ErrCode))
                exitcode = e.ErrCode
                pass
            if hasattr(e, 'Message'):
                self.log.fatal("unoconv: UnoException during %s phase:\n%s" %
                               (phase, e.Message))
                exitcode = 5
            else:
                self.log.fatal("unoconv: UnoException during %s phase in %s" %
                               (phase, repr(e.__class__)))
                exitcode = 2
                pass

        return exitcode
Пример #32
0
def main():
    retVal = 0
    doc = None
    stdout = False

    try:
        opts, args = getopt.getopt(
            sys.argv[1:], "hc:",
            ["help", "connection-string=", "html", "pdf", "stdout"])
        url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
        filterName = "Text (Encoded)"
        extension = "txt"
        for o, a in opts:
            if o in ("-h", "--help"):
                usage()
                sys.exit()
            if o in ("-c", "--connection-string"):
                url = "uno:" + a + ";urp;StarOffice.ComponentContext"
            if o == "--html":
                filterName = "HTML (StarWriter)"
                extension = "html"
            if o == "--pdf":
                filterName = "writer_pdf_Export"
                extension = "pdf"
            if o == "--stdout":
                stdout = True

        if not len(args):
            usage()
            sys.exit()

        ctxLocal = uno.getComponentContext()
        smgrLocal = ctxLocal.ServiceManager

        resolver = smgrLocal.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", ctxLocal)
        ctx = resolver.resolve(url)
        smgr = ctx.ServiceManager

        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",
                                                 ctx)

        cwd = systemPathToFileUrl(getcwd())
        outProps = (PropertyValue("FilterName", 0, filterName,
                                  0), PropertyValue("Overwrite", 0, True, 0),
                    PropertyValue("OutputStream", 0, OutputStream(), 0))

        inProps = PropertyValue("Hidden", 0, True, 0),
        for path in args:
            try:
                fileUrl = absolutize(cwd, systemPathToFileUrl(path))
                doc = desktop.loadComponentFromURL(fileUrl, "_blank", 0,
                                                   inProps)

                #Get list structures
                c = doc.NumberingRules.Count
                lists = dict()
                for ruleNum in range(0, c):

                    numberingRule = doc.NumberingRules.getByIndex(ruleNum)
                    listId = numberingRule.DefaultListId
                    lists[listId] = []
                    for i in range(0, numberingRule.Count):
                        lists[listId].append(dict())

                        rule = numberingRule.getByIndex(i)
                        for prop in rule:
                            lists[listId][i][prop.Name] = prop.Value

#print lists

                curs = doc.Text.createTextCursor()
                while curs.gotoNextParagraph(False):
                    print "Paragraph:"
                    left = curs.ParaLeftMargin
                    lid = curs.ListId
                    if lid <> "":
                        print lid
                        #print dir(curs)
                        level = curs.OutlineLevel
                        print "Level %s" % str(level)
                        left = lists[lid][level]["IndentAt"]
                        #print lists[lid][level]
                    print "LeftMargin %s" % str(left)
                    bookmark = doc.createInstance("com.sun.star.text.Bookmark")
                    bookmark.setName("left-margin:%s-" % str(left))
                    doc.Text.insertTextContent(curs, bookmark, False)

#print dir(bookmark)

                print dir(doc.Text)

                if not doc:
                    raise UnoException(
                        "Couldn't open stream for unknown reason", None)

                if not stdout:
                    (dest, ext) = splitext(path)
                    dest = dest + "." + extension
                    destUrl = absolutize(cwd, systemPathToFileUrl(dest))
                    sys.stderr.write(destUrl + "\n")
                    doc.storeToURL(destUrl, outProps)
                else:
                    doc.storeToURL("private:stream", outProps)
            except IOException, e:
                sys.stderr.write("Error during conversion: " + e.Message +
                                 "\n")
                retVal = 1
            except UnoException, e:
                sys.stderr.write("Error (" + repr(e.__class__) +
                                 ") during conversion:" + e.Message + "\n")
                retVal = 1
Пример #33
0
    def convert(self, inputfn):
        global exitcode

        doc = None
        outputfmt = self.getformat(inputfn)

        if op.verbose > 0:
            print >> sys.stderr, 'Input file:', inputfn

        if not os.path.exists(inputfn):
            print >> sys.stderr, 'unoconv: file `%s\' does not exist.' % inputfn
            exitcode = 1

        try:
            ### Load inputfile
            inputprops = (PropertyValue("Hidden", 0, True, 0), )

            inputurl = unohelper.absolutize(
                self.cwd, unohelper.systemPathToFileUrl(inputfn))
            doc = self.desktop.loadComponentFromURL(inputurl, "_blank", 0,
                                                    inputprops)

            if not doc:
                raise UnoException("File could not be loaded by OpenOffice",
                                   None)


#            standard = doc.getStyleFamilies().getByName('PageStyles').getByName('Standard')
#            pageSize = Size()
#            pageSize.Width=1480
#            pageSize.Height=3354
#            standard.setPropertyValue('Size', pageSize)

            error(1, "Selected output format: %s" % outputfmt)
            # pylint: disable=E1103
            # outputfmt is an instance of the class Fmt.
            error(1, "Selected ooffice filter: %s" % outputfmt.filter)
            error(1, "Used doctype: %s" % outputfmt.doctype)

            ####            ### Write outputfile
            ####            outputprops = (
            ####                    PropertyValue( "FilterName", 0, outputfmt.filter, 0),
            ####                    PropertyValue( "Overwrite", 0, True, 0 ),
            #####                    PropertyValue( "Size", 0, "A3", 0 ),
            ####                    PropertyValue( "OutputStream", 0, OutputStream(), 0 ),
            ####                   )

            ### BEG Invenio customizations
            outputprops = [
                PropertyValue("FilterName", 0, outputfmt.filter, 0),
                PropertyValue("Overwrite", 0, True, 0),
                PropertyValue("OutputStream", 0, OutputStream(), 0),
            ]
            if outputfmt.filter == 'Text (encoded)':
                ## To enable UTF-8
                outputprops.append(
                    PropertyValue("FilterFlags", 0, "UTF8, LF", 0))
            elif outputfmt.filter == 'writer_pdf_Export':
                ## To enable PDF/A
                outputprops.append(PropertyValue("SelectPdfVersion", 0, 1, 0))

            outputprops = tuple(outputprops)
            ### END Invenio customizations

            if not op.stdout:
                (outputfn, ext) = os.path.splitext(inputfn)
                ### BEG Invenio customizations
                if op.outputfile:
                    outputfn = op.outputfile
                elif not op.outputpath:  ### END Invenio customizations
                    outputfn = outputfn + '.' + outputfmt.extension
                else:
                    outputfn = os.path.join(
                        op.outputpath,
                        os.path.basename(outputfn) + '.' + outputfmt.extension)
                outputurl = unohelper.absolutize(
                    self.cwd, unohelper.systemPathToFileUrl(outputfn))
                doc.storeToURL(outputurl, outputprops)
                error(1, "Output file: %s" % outputfn)
            else:
                doc.storeToURL("private:stream", outputprops)

            # pylint: enable=E1103

            doc.dispose()
            doc.close(True)

        except SystemError, e:
            error(0, "unoconv: SystemError during conversion: %s" % e)
            error(
                0,
                "ERROR: The provided document cannot be converted to the desired format."
            )
            exitcode = 1
Пример #34
0
    def getPDFFromOfficeDocument(self):
        #print 'in getPDFFROMofficeDocument before calling generic storePath'
        if self.getConversionState() == 'CANCELLED':
            return ''
        storePath = self.getGenericStorePath()
        #print storePath+'in getPDFFROMofficeDocument'
        infile = self.location
        #print infile
        local = uno.getComponentContext()
        resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local)
        resolveUrl = "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext"
        context = resolver.resolve(resolveUrl)
        try:
            desktopService = context.ServiceManager.createInstance("com.sun.star.frame.Desktop")
          #  print 'desktop service done'
        except:
            cherrypy.log('Error in getting desktop service... meeting ID = ' + self.meetingID + ' and docID = ' + self.docID)
            self.setErrorCode(7909)
            return ''

        if self.getConversionState() == 'CANCELLED':
            return ''

        if sys.platform.startswith('win'):
            outfile = storePath + 'conv.pdf'
        else:
            outfile = storePath + '/conv.pdf'

        outtempFile = storePath + '\\conv.ps'

        args = (PropertyValue("Hidden", 0, True, 0),)
        url = unohelper.systemPathToFileUrl(self.location)
        try:
            sourceFile = desktopService.loadComponentFromURL(url,"_blank", 0, args)
            #print sourceFile
            #iPageCount = sourceFile.getDrawPages().getCount()
            #self.totalPageCount = iPageCount
            #print self.totalPageCount
        except:
            cherrypy.log('Error has occured in loadComponentFromURL... meeting ID = ' + self.meetingID + ' and docID = ' + self.docID)
            self.setErrorCode(7406)
            return ''

        if self.getConversionState() == 'CANCELLED':
            return ''

        filterName = PropertyValue()
        filterName.Name = 'FilterName'
        filterName.Value = 'impress_pdf_Export'
        storePath = self.getGenericStorePath()
        pdfPath = unohelper.systemPathToFileUrl(storePath)+ 'conv.pdf'
        #print pdfPath + ' in systemPathToFileUrl'
        urlData = PropertyValue()
        urlData.Name = 'URL'
        urlData.Value = pdfPath
        #print pdfPath
        try:
            sourceFile.storeToURL(unohelper.absolutize(unohelper.systemPathToFileUrl(self.getGenericStorePath()), unohelper.systemPathToFileUrl('conv.pdf')), (filterName,))
	    #sourceFile.storeToURL(pdfPath, (filterName,))
        except:
            cherrypy.log('Error in exporting document to PDF... meeting ID = ' + self.meetingID + ' and docID = ' + self.docID)
            self.setErrorCode(7407)
            storePath = ''

        if self.getConversionState() == 'CANCELLED':
            return ''

        try:
            sourceFile.dispose()
        except:
            cherrypy.log('Error in disposing document... meeting ID = ' + self.meetingID + ' and docID = ' + self.docID)
            pass

        return storePath
Пример #35
0
    ### Update document indexes
    try:
        document.refresh()
        indexes = document.getDocumentIndexes()
    except AttributeError:
        # the document doesn't implement the XRefreshable and/or
        # XDocumentIndexesSupplier interfaces
        pass
    else:
        for i in range(0, indexes.getCount()):
            indexes.getByIndex(i).update()

    outputprops = UnoProps(FilterName=fileOption.format, Overwrite=True)
    if fileOption.formatOptions != '':
        outputprops += UnoProps(FilterOptions=fileOption.formatOptions)
    outputurl = unohelper.absolutize(cwd, unohelper.systemPathToFileUrl(fileOption.output) )

    try:
        document.storeToURL(outputurl, tuple(outputprops) )
    except:
        sendErrorOrExit('401') # could not convert document
        document.dispose()
        document.close(True)
        return

    document.dispose()
    document.close(True)
    send('200') ### Document converted


def listen():
Пример #36
0
def main():
    retVal = 0
    doc = None
    stdout = False

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:",
            ["help", "connection-string=" , "html", "pdf", "stdout" ])
        url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
        filterName = "Text (Encoded)"
        extension  = "txt"
        for o, a in opts:
            if o in ("-h", "--help"):
                usage()
                sys.exit()
            if o in ("-c", "--connection-string" ):
                url = "uno:" + a + ";urp;StarOffice.ComponentContext"
            if o == "--html":
                filterName = "HTML (StarWriter)"
                extension  = "html"
            if o == "--pdf":
                filterName = "writer_pdf_Export"
                extension  = "pdf"
	    if o == "--stdout":
	    	stdout = True
                
        if not len( args ):
            usage()
            sys.exit()
              
        ctxLocal = uno.getComponentContext()
        smgrLocal = ctxLocal.ServiceManager

        resolver = smgrLocal.createInstanceWithContext(
                 "com.sun.star.bridge.UnoUrlResolver", ctxLocal )
        ctx = resolver.resolve( url )
        smgr = ctx.ServiceManager

        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx )

        cwd = systemPathToFileUrl( getcwd() )
        outProps = (
            PropertyValue( "FilterName" , 0, filterName , 0 ),
	    PropertyValue( "Overwrite" , 0, True , 0 ),
            PropertyValue( "OutputStream", 0, OutputStream(), 0)
	)
	    
        inProps = PropertyValue( "Hidden" , 0 , True, 0 ),
        for path in args:
            try:
                fileUrl = absolutize( cwd, systemPathToFileUrl(path) )
                doc = desktop.loadComponentFromURL( fileUrl , "_blank", 0, inProps )

                if not doc:
                    raise UnoException( "Couldn't open stream for unknown reason", None )

		if not stdout:
                    (dest, ext) = splitext(path)
                    dest = dest + "." + extension
                    destUrl = absolutize( cwd, systemPathToFileUrl(dest) )
                    sys.stderr.write(destUrl + "\n")
                    doc.storeToURL(destUrl, outProps)
		else:
		    doc.storeToURL("private:stream",outProps)
            except IOException, e:
                sys.stderr.write( "Error during conversion: " + e.Message + "\n" )
                retVal = 1
            except UnoException, e:
                sys.stderr.write( "Error ("+repr(e.__class__)+") during conversion:" + e.Message + "\n" )
                retVal = 1
Пример #37
0
    def getModuleFromUrl(self, url):
        if DEBUG:
            print("pythonloader: interpreting url " + url)
        protocol, dependent = splitUrl(url)
        if "vnd.sun.star.expand" == protocol:
            exp = self.ctx.getValueByName(
                "/singletons/com.sun.star.util.theMacroExpander")
            url = exp.expandMacros(dependent)
            protocol, dependent = splitUrl(url)

        if DEBUG:
            print("pythonloader: after expansion " + protocol + ":" +
                  dependent)

        try:
            if "file" == protocol:
                # remove \..\ sequence, which may be useful e.g. in the build env
                url = unohelper.absolutize(url, url)

                # did we load the module already ?
                mod = g_loadedComponents.get(url)
                if not mod:
                    mod = types.ModuleType("uno_component")

                    # check for pythonpath.zip beside .py files
                    checkForPythonPathBesideComponent(url[0:url.rfind('/')])

                    # read the file
                    filename = unohelper.fileUrlToSystemPath(url)

                    with open(filename, encoding='utf_8') as fileHandle:
                        src = fileHandle.read().replace("\r", "")
                        if not src.endswith("\n"):
                            src = src + "\n"

                        # compile and execute the module
                        codeobject = compile(src, encfile(filename), "exec")
                        mod.__file__ = filename
                        exec(codeobject, mod.__dict__)
                        g_loadedComponents[url] = mod
                return mod
            elif "vnd.openoffice.pymodule" == protocol:
                nSlash = dependent.rfind('/')
                if -1 != nSlash:
                    path = unohelper.fileUrlToSystemPath(dependent[0:nSlash])
                    dependent = dependent[nSlash + 1:len(dependent)]
                    if not path in sys.path:
                        sys.path.append(path)
                mod = __import__(dependent)
                path_component, dot, rest = dependent.partition('.')
                while dot == '.':
                    path_component, dot, rest = rest.partition('.')
                    mod = getattr(mod, path_component)
                return mod
            else:
                if DEBUG:
                    print("Unknown protocol '" + protocol + "'")
                raise RuntimeException(
                    "PythonLoader: Unknown protocol " + protocol + " in url " +
                    url, self)
        except Exception as e:
            if DEBUG:
                print("Python import exception " + str(type(e)) + " message " +
                      str(e) + " args " + str(e.args))
            raise RuntimeException(
                "Couldn't load " + url + " for reason " + str(e), None)
        return None
Пример #38
0
 def _url(self, url):
     return unohelper.absolutize(self.cwd, unohelper.systemPathToFileUrl(url))
Пример #39
0
    cursorInTextFrame, "The first line in the newly created text frame.", 0)
textInTextFrame.insertString(
    cursorInTextFrame,
    "\nWith this second line the height of the frame raises.", 0)
text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0)

cursor.setPropertyValue("CharColor", 65536)
cursor.setPropertyValue("CharShadowed", uno.Bool(0))

text.insertString(cursor, " That's all for now !!", 0)

cursor.setPropertyValue("CharWeight", BOLD)
text.insertString(cursor, "bold text ", 0)

cursor.setPropertyValue("CharPosture", ITALIC)
text.insertString(cursor, "italic bold text ", 0)

cursor.setPropertyValue("CharWeight", NORMAL)
text.insertString(cursor, "italic text", 0)

#saveProperty = createStruct("com.sun.star.beans.PropertyValue")
#saveProperty.Name = "FilterName"
#saveProperty.Value = "MS Word 97"

outputfile = "/tmp/ootest.doc"
cwd = systemPathToFileUrl(getcwd())
destFile = absolutize(cwd, systemPathToFileUrl(outputfile))
print destFile
doc.storeAsURL(destFile, ())
doc.dispose()
Пример #40
0
def main():
    retVal = 0
    doc = None
    stdout = False

    try:
        stdout = True

        ctxLocal = uno.getComponentContext()
        smgrLocal = ctxLocal.ServiceManager

        resolver = smgrLocal.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", ctxLocal)
        url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
        ctx = resolver.resolve(url)
        smgr = ctx.ServiceManager
        msp = ctx.getValueByName(
            "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory"
        )
        sp = msp.createScriptProvider("")

        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",
                                                 ctx)

        cwd = systemPathToFileUrl(getcwd())
        outProps = (
            #            PropertyValue( "FilterName" , 0, filterName , 0 ),
            PropertyValue("Overwrite", 0, True, 0),
            PropertyValue("OutputStream", 0, OutputStream(), 0))

        inProps = PropertyValue("Hidden", 0, True, 0),
        # 97, 169, 211
        wrong = []
        for index in range(1, 1338):
            path = "lab_%s_file.doc" % index
            try:
                fileUrl = absolutize(cwd, systemPathToFileUrl(path))
                doc = desktop.loadComponentFromURL(fileUrl, "_blank", 0,
                                                   inProps)
                #                print(doc)

                # Find macro name
                macro_name = list(
                    doc.BasicLibraries.getByName('Project').getElementNames())
                macro_name.remove('ThisDocument')
                if 'Module1' in macro_name:
                    macro_name.remove('Module1')
                #print(macro_name)
                assert (len(macro_name) == 1)
                macro_name = macro_name[0]
                # print("Doc[%s] : Found macro name %s, fetch it" % (index, macro_name))

                # Get macro
                macro_code = doc.BasicLibraries.getByName('Project').getByName(
                    macro_name)
                assert ("ActiveDocument.Variables" in macro_code)

                # Get User defined variable
                property_name = [
                    l for l in macro_code.split('\n')
                    if "ActiveDocument.Variables" in l
                ][0].split('"')[1]
                assert (property_name != '')
                # print("Doc[%s]: Found property name %s" % (index, property_name))

                # Find property value
                property_value = doc.getDocumentProperties(
                ).getUserDefinedProperties().getPropertyValue(property_name)
                # print("Doc[%s]: Found property value of length %s" % (index, len(property_value)))

                macro_code = re.sub(re.compile("Active.*$", re.MULTILINE),
                                    '"%s"' % property_value, macro_code)

                with open('/tmp/%s.macro.vba' % index, 'w') as output:
                    # print("Doc[%s]: Write updated macro to macros/%s.macro.vba" % (index, index))
                    output.write(macro_code)

                with open('/tmp/%s.macro.py' % index, 'w') as output:
                    # print("Doc[%s]: Write python macro to macros/%s.macro.py" % (index, index))
                    output.write(vba2py(macro_code))

#                scriptx = sp.getScript('vnd.sun.star.script:Standard.Module1.Main?language=Basic&location=application')
#                print(scriptx)
                if not doc:
                    raise UnoException(
                        "Couldn't open stream for unknown reason", None)
                else:
                    doc.dispose()

        #        if not stdout:
        #            (dest, ext) = splitext(path)
        #            dest = dest + "." + extension
        #            destUrl = absolutize( cwd, systemPathToFileUrl(dest) )
        #            sys.stderr.write(destUrl + "\n")
        #            doc.storeToURL(destUrl, outProps)
        #        else:
        #            doc.storeToURL("private:stream",outProps)
            except IOException as e:
                sys.stderr.write("Error during conversion: " + e.Message +
                                 "\n")
                retVal = 1
            except UnoException as e:
                sys.stderr.write("Error (" + repr(e.__class__) +
                                 ") during conversion:" + e.Message + "\n")
                retVal = 1
#            except Exception as e:
#                sys.stderr.write("Assertion error parsing document %s . Skipping it : %s" % (index, e))
#                wrong.append(index)
#                print(doc)
#                sys.exit(1)

    except UnoException as e:
        sys.stderr.write("Error (" + repr(e.__class__) + ") :" + e.Message +
                         "\n")
        retVal = 1
    except getopt.GetoptError as e:
        sys.stderr.write(str(e) + "\n")
        usage()
        retVal = 1