Exemple #1
0
    def convert(self):
        """Convert the document"""

        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext(
                       'com.sun.star.bridge.UnoUrlResolver', localContext )
        ctx = resolver.resolve(
                       'uno:socket,host=localhost,port=2002;'
                       'urp;StarOffice.ComponentContext')
        smgr = ctx.ServiceManager
        desktop = smgr.createInstanceWithContext(
                       'com.sun.star.frame.Desktop', ctx)

        # load the document
        url = unohelper.systemPathToFileUrl(self.fullname)
        doc = desktop.loadComponentFromURL(url, '_blank', 0, ())

        filterName = 'swriter: HTML (StarWriter)'
        storeProps = (
                       PropertyValue('FilterName', 0, filterName, 0),
                      )

        # pre-create a empty file for security reason
        url = unohelper.systemPathToFileUrl(self.outputfile)
        doc.storeToURL(url, storeProps)

        try:
            doc.close(True)
        except com.sun.star.util.CloseVetoException:
            pass

        # maigic to release some resource
        ctx.ServiceManager
Exemple #2
0
    def convert(self):
        """Convert the document"""

        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext(
            "com.sun.star.bridge.UnoUrlResolver", localContext
        )
        ctx = resolver.resolve("uno:socket,host=localhost,port=2002;" "urp;StarOffice.ComponentContext")
        smgr = ctx.ServiceManager
        desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)

        # load the document
        url = unohelper.systemPathToFileUrl(self.fullname)
        doc = desktop.loadComponentFromURL(url, "_blank", 0, ())

        filterName = "swriter: HTML (StarWriter)"
        storeProps = (PropertyValue("FilterName", 0, filterName, 0),)

        # pre-create a empty file for security reason
        url = unohelper.systemPathToFileUrl(self.outputfile)
        doc.storeToURL(url, storeProps)

        try:
            doc.close(True)
        except CloseVetoException:
            pass

        # maigic to release some resource
        ctx.ServiceManager
Exemple #3
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
Exemple #4
0
 def exportDocUno(self, filepath, pdfname, pdfproperties):
     debug("Export to pdf")
     #calculate the url
     self._cwd = systemPathToFileUrl(dirname(filepath))
     fileUrl = systemPathToFileUrl(filepath)
     inProps = PropertyValue("Hidden" , 0 , True, 0),
     
     #load the document
     debug("load")
     self._doc = self._desktop.loadComponentFromURL(fileUrl, '_blank', 0, inProps)
     self._doc.reformat()
     #try:
     #    self._exportToPDF('/tmp/nocreate')
     #except:
     #    pass
     f = self._doc.CurrentController.Frame
     debug("repaginate")
     self.dispatcher.executeDispatch(f, ".uno:Repaginate", "", 0, ())
     debug("update index")
     self._updateIndex()
     debug("read properties")
     self._readProperties(pdfproperties)
     debug("export")
     self._exportToPDF(pdfname)
     debug("dispose")
     self._doc.dispose()
     debug("end pdf generation")
Exemple #5
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
def main():
    retVal = 0
    doc = None

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:",
                                   ["help", "connection-string=", "html"])
        format = None
        url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
        filterName = "Text (Encoded)"
        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)"

        print filterName
        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("OutputStream", 0, OutputStream(), 0))
        inProps = PropertyValue("Hidden", 0, True, 0),
        for path in args:
            try:
                fileUrl = uno.absolutize(cwd, systemPathToFileUrl(path))
                doc = desktop.loadComponentFromURL(fileUrl, "_blank", 0,
                                                   inProps)

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

                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
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)
Exemple #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)
Exemple #9
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
Exemple #10
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" ) )
Exemple #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"))
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()
Exemple #13
0
def main():
    retVal = 0
    doc = None

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:",["help", "connection-string=" , "html"])
        format = None
        url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext"
        filterName = "Text (Encoded)"
        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)"
            
        print filterName
        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( "OutputStream",0, OutputStream(),0))
        inProps = PropertyValue( "Hidden" , 0 , True, 0 ),
        for path in args:
            try:
                fileUrl = uno.absolutize( cwd, systemPathToFileUrl(path) )
                doc = desktop.loadComponentFromURL( fileUrl , "_blank", 0,inProps)

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

                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
Exemple #14
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
Exemple #15
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()
def main():
    ctx = XSCRIPTCONTEXT.getComponentContext()  # コンポーネントコンテクストの取得。
    smgr = ctx.getServiceManager()  # サービスマネージャーの取得。
    os.chdir("..")  # 一つ上のディレクトリに移動。
    simplefileaccess = smgr.createInstanceWithContext(
        "com.sun.star.ucb.SimpleFileAccess", ctx)  # SimpleFileAccess
    source_path = os.path.join(os.getcwd(), "src", "Scripts",
                               "python")  # コピー元フォルダのパスを取得。
    source_fileurl = unohelper.systemPathToFileUrl(source_path)  # fileurlに変換。
    if not simplefileaccess.exists(source_fileurl):  # ソースにするフォルダがないときは終了する。
        print("The source macro folder does not exist.")
        return
    ods = glob.glob("*.ods")[0]  # odsファイルを取得。最初の一つのみ取得。
    systempath = os.path.join(os.getcwd(), ods)  # odsファイルのフルパス。
    doc_fileurl = unohelper.systemPathToFileUrl(systempath)  # fileurlに変換。
    desktop = ctx.getByName(
        '/singletons/com.sun.star.frame.theDesktop')  # デスクトップの取得。
    flg = isComponentLoaded(desktop, doc_fileurl)  # ドキュメントが開いていたら保存して閉じる。
    python_pkgurl = getVndSunStarPkgUrl(ctx, smgr, doc_fileurl)  # pkgurlの取得。
    if simplefileaccess.exists(
            python_pkgurl
    ):  # 埋め込みマクロフォルダがすでに存在する時。simplefileaccess.kill(pkgurl)では削除できない。
        package = smgr.createInstanceWithArgumentsAndContext(
            "com.sun.star.packages.Package", (doc_fileurl, ),
            ctx)  # Package。第2引数はinitialize()メソッドで後でも渡せる。
        docroot = package.getByHierarchicalName("/")  # /Scripts/pythonは不可。
        for name in docroot["Scripts"]["python"].getElementNames(
        ):  # すでに存在する埋め込みマクロフォルダの各要素を削除。
            del docroot["Scripts"]["python"][name]
        package.commitChanges()  # ファイルにパッケージの変更を書き込む。manifest.xmlも編集される。
    else:  # 埋め込みマクロフォルダが存在しない時。
        propertyvalues = PropertyValue(Name="Hidden", Value=True),
        doc = desktop.loadComponentFromURL(
            doc_fileurl, "_blank", 0, propertyvalues)  # ドキュメントをバックグラウンドで開く。
        if doc is None:  # ドキュメントが壊れているときなどはNoneになる。
            print("{} may be corrupted.".format(ods), file=sys.stderr)
            sys.exit()
        createEmbeddedMacroFolder(
            ctx, smgr, simplefileaccess,
            doc)  # 埋め込みマクロフォルダを新規作成。開いているドキュメントにしか作成できない。
        doc.store()  # ドキュメントを保存する。
        doc.close(True)  # ドキュメントを閉じる。
    simplefileaccess.copy(
        source_fileurl, python_pkgurl
    )  # 埋め込みマクロフォルダにコピーする。開いているドキュメントでは書き込みが反映されない時があるので閉じたドキュメントにする。
    # 	if flg:  # ドキュメントが開いていた時はマクロを有効にして開き直す。しかしこれではモジュールが更新されない。
    # 		propertyvalues = PropertyValue(Name = "MacroExecutionMode", Value=MacroExecMode.ALWAYS_EXECUTE_NO_WARN),  # マクロを実行可能にする。
    # 		desktop.loadComponentFromURL(doc_fileurl, "_blank", 0, propertyvalues)  # ドキュメントを開く。
    print("Replaced the embedded macro folder in {} with {}.".format(
        ods, source_path))
def Xml2Pdf(conf, input, output):
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", localContext)
    ctx = resolver.resolve(
        "uno:socket,host=127.0.0.1,port=3662;urp;StarOffice.ComponentContext")
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
    adressDoc = systemPathToFileUrl(input["doc"]["value"])
    propFich = PropertyValue("Hidden", 0, True, 0),
    try:
        myDocument = desktop.loadComponentFromURL(adressDoc, "_blank", 0,
                                                  propFich)
#Prefer to create a new document without any style ?
#myDocument = desktop.loadComponentFromURL("private:factory/writer","_blank",0,propFich)
    except:
        conf["lenv"]["message"] = 'Unable to load input document'
        return 4
    text = myDocument.Text
    cursor = text.createTextCursor()
    cursor.gotoStart(0)
    cursor.gotoEnd(1)
    xmldoc = minidom.parseString(input['xml']['value'])

    if xmldoc.hasChildNodes():
        for i in xmldoc.childNodes:
            if i.nodeType == 1:
                cursor.ParaStyleName = "Title"
                text.insertString(cursor, i.nodeName, 0)
                text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0)
                #print >> sys.stderr,' * 1st level' + i.nodeName
                if i.hasChildNodes():
                    for j in i.childNodes:
                        printChildren(cursor, text, j, 2, '')

    tmp = myDocument.StyleFamilies.getByName("NumberingStyles")

    tmp1 = tmp.getByName("Puce 1")

    prop1Fich = (PropertyValue("FilterName", 0, "writer_pdf_Export",
                               0), PropertyValue("Overwrite", 0, True, 0))
    outputDoc = systemPathToFileUrl("/tmp/output.pdf")
    myDocument.storeToURL(outputDoc, prop1Fich)

    myDocument.close(True)
    ctx.ServiceManager
    output["Document"]["value"] = open('/tmp/output.pdf', 'r').read()
    print >> sys.stderr, len(output["Document"]["value"])
    return 3
Exemple #18
0
def main(host, port, path, pagecountlimit):
    retVal = 0
    pagecountlimit = '50'
    doc = None

    url = "uno:socket,host=%s,port=%d;urp;StarOffice.ComponentContext" % (host,
                                                                          port)

    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, "StarOffice XML (Writer)" , 0 ),
        PropertyValue("OutputStream", 0, OutputStream(), 0), )
    inProps = (PropertyValue("Hidden", 0, True, 0), )
    try:
        fileUrl = uno.absolutize(cwd, systemPathToFileUrl(path))
        doc = desktop.loadComponentFromURL(fileUrl, "_blank", 0, inProps)

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

        # pdb.set_trace()

        try:
            cursor = doc.getCurrentController().getViewCursor()
            cursor.jumpToLastPage()
            pagecount = cursor.getPage()
            if pagecount > int(pagecountlimit):
                raise UnoException(
                    "Input document has %d pages which exceeeds the page count limit of %d."
                    % (pagecount, int(pagecountlimit)), None)
        except AttributeError:
            # opened picture files will not behave, but do not need to have their page counted
            pass

        doc.storeToURL("private:stream", outProps)
    except IOException, e:
        sys.stderr.write("Error during conversion: " + e.Message + "\n")
        retVal = 1
Exemple #19
0
 def loadImage(self, image_name, image_file):
     oBitmaps = self.doc.createInstance("com.sun.star.drawing.BitmapTable")
     try:
         oBitmaps.insertByName(image_name, systemPathToFileUrl(image_file))
     except Exception as e:
         print(": > " + e.Message, file=sys.stderr)
     return oBitmaps.getByName(image_name)
Exemple #20
0
    def save(self, fileUrl):
        if not self.doc:
            raise "Failed to save cause there is no document"
        if fileUrl.startswith("file://"):
            fileUrl = fileUrl[7:]
        if not fileUrl:
            raise "Failed to save cause invalid file \"%s\" defined." % fileUrl

        try:
            import unohelper
            outUrl = unohelper.systemPathToFileUrl(fileUrl)
            outProps = []

            fileExt = os.path.splitext(fileUrl)[1].lower()
            if fileExt == '.txt' or fileExt == '.text':
                outProps.append( UnoPropertyValue('FilterName', 0, 'Text (encoded)', 0) )
            elif fileExt == '.htm' or fileExt == '.html':
                outProps.append( UnoPropertyValue('FilterName', 0, 'HTML (StarWriter)', 0) )
            elif fileExt == '.pdf':
                outProps.append( UnoPropertyValue('FilterName', 0, 'writer_pdf_Export', 0) )
            #else: opendocument...

            print "Save to: %s" % outUrl
            self.doc.storeToURL(outUrl, tuple(outProps))
        except:
            traceback.print_exc()
Exemple #21
0
    def getResultUrl(self):
        '''Returns the path of the result file in the format needed by OO. If
           the result type and the input type are the same (ie the user wants to
           refresh indexes or some other action and not perform a real
           conversion), the result file is named
                           <inputFileName>.res.<resultType>.

           Else, the result file is named like the input file but with a
           different extension:
                           <inputFileName>.<resultType>
        '''
        import unohelper
        baseName = os.path.splitext(self.docPath)[0]
        if self.resultType != self.inputType:
            res = '%s.%s' % (baseName, self.resultType)
        else:
            res = '%s.res.%s' % (baseName, self.resultType)
        try:
            f = open(res, 'w')
            f.write('Hello')
            f.close()
            os.remove(res)
            return unohelper.systemPathToFileUrl(res)
        except (OSError, IOError), ioe:
            raise ConverterError(CANNOT_WRITE_RESULT % (res, ioe))
Exemple #22
0
def DumpNamedSheet(XmlFileName, CsvFileName, SheetName, Separator):
    
    
    model, desktop = LaunchCalcWithFile(XmlFileName)
    
    
    sheet = model.Sheets.getByName(SheetName)
    
    
    # Now save it in CSV format.
    filename = CsvFileName
    os.path.expanduser(filename)
    filename = os.path.abspath(filename)
    out_props = (
            PropertyValue("FilterName", 0, "Text - txt - csv (StarCalc)", 0),
            PropertyValue("Overwrite", 0, True, 0),
            PropertyValue("Separator", 0, Separator, 0),
            )
    csv_url = unohelper.systemPathToFileUrl(filename)
    model.storeToURL( csv_url, out_props)
    
    time.sleep(1)
    model.dispose()
    ShutdownCalc( desktop )
    
    
    pass
def OdtConverter(conf,inputs,outputs):
	# get the uno component context from the PyUNO runtime  
	localContext = uno.getComponentContext()

	# create the UnoUrlResolver 
	# on a single line
	resolver = 	localContext.ServiceManager.createInstanceWithContext	("com.sun.star.bridge.UnoUrlResolver", localContext )

	# connect to the running office                                 
	ctx = resolver.resolve( conf["oo"]["server"].replace("::","=")+";urp;StarOffice.ComponentContext" )
	smgr = ctx.ServiceManager

	# get the central desktop object
	desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)

	# get the file name
	adressDoc=systemPathToFileUrl(conf["main"]["dataPath"]+"/"+inputs["InputDoc"]["value"])

	propFich=PropertyValue("Hidden", 0, True, 0),

	myDocument=0
	try:
	    myDocument = desktop.loadComponentFromURL(adressDoc,"_blank",0,propFich)
	except CannotConvertException, e:
	    print >> sys.stderr,  'Impossible de convertir le fichier pour les raisons suivantes : \n'
	    print >> sys.stderr,  e
	    sys.exit(0)
Exemple #24
0
 def create(self, data, filename, unlock):
     res = self.get_data("api/create/", data)
     if not filename:
         return False, "Bad file name"
     if res["result"] != "ok":
         return False, res["error"]
     else:
         doc = res["object"]
         # create a new doc
         rep = os.path.join(self.PLUGIN_DIR, doc["type"], doc["reference"],
                            doc["revision"])
         try:
             os.makedirs(rep, 0700)
         except os.error:
             # directory already exists, just ignores the exception
             pass
         gdoc = self.desktop.getCurrentComponent()
         path = os.path.join(rep, filename)
         gdoc.storeAsURL(unohelper.systemPathToFileUrl(path), ())
         doc_file = self.upload_file(doc, path)
         self.add_managed_file(doc, doc_file, path)
         self.load_file(doc, doc_file["id"], path)
         if not unlock:
             self.get_data("api/object/%s/lock/%s/" %
                           (doc["id"], doc_file["id"]))
         else:
             self.send_thumbnail(gdoc)
             self.forget(gdoc, False)
         return True, ""
Exemple #25
0
    def __init__(self, server='127.0.0.1', port='2002'):
        connection = ("socket,host=%s,port=%s,tcpNoDelay=1;urp;StarOffice.ComponentContext" %
                      (server, port))

        # Do the LibreOffice component dance
        self.context = uno.getComponentContext()
        self.svcmgr = self.context.ServiceManager
        resolver = self.svcmgr.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver",
                                                         self.context)

        # Test for an existing connection
        unocontext = None
        while not unocontext:
            try:
                unocontext = resolver.resolve("uno:%s" % connection)
            except NoConnectException:
                logger.error('No soffice instance is running.')
                sleep(1)

        if not unocontext:
            sys.exit(1)

        # And some more LibreOffice magic
        unosvcmgr = unocontext.ServiceManager
        self.desktop = unosvcmgr.createInstanceWithContext("com.sun.star.frame.Desktop", unocontext)
        self.cwd = unohelper.systemPathToFileUrl(os.getcwd())
Exemple #26
0
	def actionPerformed(self, actionevent):	
		cmd = actionevent.ActionCommand
		ctx, smgr, configurationprovider, css, properties, nodepath, simplefileaccess = self.consts
		dialog = self.dialog
		if cmd=="folderpicker":
			fixedtext = dialog.getControl("RefDir")
			path = fixedtext.getText()  # システムパスが返ってくる。
			folderpicker = smgr.createInstanceWithContext("com.sun.star.ui.dialogs.FolderPicker", ctx)
			if os.path.exists(path):  # pathが存在するとき
				fileurl = unohelper.systemPathToFileUrl(path)  # システムパスをfileurlに変換する。
				folderpicker.setDisplayDirectory(fileurl)  # フォルダ選択ダイアログに設定する。
			folderpicker.setTitle(_("Select ref folder"))
			if folderpicker.execute()==OK:
				fileurl = folderpicker.getDirectory()
				checkbox = dialog.getControl("OffLine")
				if simplefileaccess.exists(fileurl):
					path = unohelper.fileUrlToSystemPath(fileurl)  # fileurlをシステムパスに変換する。
					checkbox.setEnable(True)
				else:
					path = "Local API Reference does not exists."
					checkbox.setEnable(False)
				fixedtext.setText(path)
		elif cmd=="restore":
			node = PropertyValue(Name="nodepath", Value="{}Defaults".format(nodepath))
			root = configurationprovider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", (node,))
			configs = root.getPropertyValues(properties)  # コンポーネントデータノードからデフォルト値を取得する。	
			toControls(dialog, toDialog(ctx, smgr, css, simplefileaccess, configs))  # 各コントロールに値を入力する。		
Exemple #27
0
def saveDocument(doc, url, _sAsPdf = '', _sAsOdt = ''):
    url = systemPathToFileUrl( url )
    _sFeedback = 'Successfully created '
    if _sAsOdt == 'write':
        try:
            odt_args = (PropertyValue('FilterName',0, 'writer8', 0),)
            doc.storeToURL(url + '.odt', odt_args)
            _sFeedback += 'Text Document (.odt) '
        except Exception as e:
            return str(e)
    try:
        doc.refresh()
    except:
        pass
    if _sAsPdf == 'write':
        try:
            properties=[]
            p=PropertyValue()
            p.Name='FilterName'
            p.Value='writer_pdf_Export'
            properties.append(p)
            doc.storeToURL(url + '.pdf',tuple(properties))
            if _sAsOdt == 'write':
                _sFeedback += 'and PDF file (.pdf)'
            else:
                _sFeedback += 'PDF file (.pdf)'
        except Exception as e:
            return str(e)
    doc.dispose()
    return _sFeedback
Exemple #28
0
def cmd_save_as(ooo_info,args):
    """
    The main diff is save as render the result
    save current document.
    TEXT
    HTML (StarWriter)
    MS Word 97
    """
    dest_file = args.split(',')[0]
    format = args.split(',')[1]
    doc = ooo_info['doc']
    dest_url = systemPathToFileUrl(dest_file)
    logger.info("save as %s from %s"%(format,dest_file))
    pp_filter = PropertyValue()
    pp_url = PropertyValue()
    pp_overwrite = PropertyValue()
    pp_selection = PropertyValue()
    pp_filter.Name = "FilterName"
    pp_filter.Value = format
    pp_url.Name = "URL"
    pp_url.Value = dest_url
    #pp_overwrite.Name = "Overwrite"
    #pp_overwrite.Value = True
    pp_selection.Name = "SelectionOnly"
    pp_selection.Value = True
    #outprop = (pp_filter, pp_url, pp_overwrite)
    outprop = (pp_filter, pp_url, pp_selection)
    doc.storeAsURL(dest_url, outprop)
    return ooo_info
Exemple #29
0
 def create(self, data, filename, unlock):
     res = self.get_data("api/create/", data)
     if not filename:
         return False, "Bad file name"
     if res["result"] != "ok":
         return False, res["error"]
     else:
         doc = res["object"]
         # create a new doc
         rep = os.path.join(self.PLUGIN_DIR, doc["type"], doc["reference"],
                            doc["revision"])
         try:
             os.makedirs(rep, 0700)
         except os.error:
             # directory already exists, just ignores the exception
             pass
         gdoc = self.desktop.getCurrentComponent()
         path = os.path.join(rep, filename)
         gdoc.storeAsURL(unohelper.systemPathToFileUrl(path), ())
         doc_file = self.upload_file(doc, path)
         self.add_managed_file(doc, doc_file, path)
         self.load_file(doc, doc_file["id"], path)
         if not unlock:
             self.get_data("api/object/%s/lock/%s/" % (doc["id"], doc_file["id"]))
         else:
             self.send_thumbnail(gdoc)
             self.forget(gdoc, False)
         return True, ""
def saveSpreadSheet(doc, url='', filters=()):
    #    doc.storeToURL(unohelper.systemPathToFileUrl(os.path.join(os.path.dirname(os.path.abspath(__file__)),'filters.ods')),())
    if doc.isModified:
        if doc.hasLocation and (not doc.isReadonly):
            doc.store()
        else:
            doc.storeAsURL(unohelper.systemPathToFileUrl(url), filters)
Exemple #31
0
def cmd_save_to(ooo_info,args):
    """
    #<toutpt> seems storeAsURL doesn t work with the filter writer_pdf_Export
    #<toutpt> on 2.0.4
    #<toutpt> working with storeToURL
    #<lgodard> toutpt : yes
    #<lgodard> toutpt: it is a feature - StoreASUrl is for filter that OOo can render
    writer_pdf_Export
    """
    dest_file = args.split(',')[0]
    format = args.split(',')[1]
    doc = ooo_info['doc']
    dest_url = systemPathToFileUrl(dest_file)
    logger.info( "save to %s from %s"%(format,dest_file))
    pp_filter = PropertyValue()
    pp_url = PropertyValue()
    pp_overwrite = PropertyValue()
    pp_filter.Name = "FilterName"
    pp_filter.Value = format
    pp_url.Name = "URL"
    pp_url.Value = dest_url
    pp_overwrite.Name = "Overwrite"
    pp_overwrite.Value = True
    outprop = (pp_filter, pp_url, pp_overwrite)
    doc.storeToURL(dest_url, outprop)
Exemple #32
0
    def AddDataBase(self, name):
        guard = OpenRTM_aist.ScopedLock(self._mutex)
        try:

            names = self.m_comp.base._context.getElementNames()
            for i in names:
                if name == str(i):
                    return False

            dbURL = self.m_comp.filepath[0] + "\\" + name + ".odb"
            if os.name == "posix":
                dbURL = self.m_comp.filepath[0] + "/" + name + ".odb"
            ofile = os.path.abspath(dbURL)

            oDB = self.m_comp.base._context.createInstance()
            oDB.URL = "sdbc:embedded:hsqldb"

            p = PropertyValue()
            properties = (p,)

            oDB.DatabaseDocument.storeAsURL(ofile, properties)

            oDS = XSCRIPTCONTEXT.getDesktop().loadComponentFromURL(
                unohelper.systemPathToFileUrl(ofile), "_blank", 0, ()
            )
            self.m_comp.base._context.registerObject(name, oDS.DataSource)
            oDS.close(True)
            del guard
            return True
        except:
            if guard:
                del guard
            return False

        raise CORBA.NO_IMPLEMENT(0, CORBA.COMPLETED_NO)
Exemple #33
0
    def createAddress(self, id):
        # get the central desktop object
        desktop = self.smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",self.ctx)
        path = os.environ['CUON_OO_DOC']
        inProps = PropertyValue( "Hidden" , 0 , True, 0 ),
        fileUrl = uno.absolutize('test.sxc' , systemPathToFileUrl(path) )
        model = desktop.loadComponentFromURL( fileUrl , "_blank", 0, inProps)


        # access the current writer document
        #model = desktop.getCurrentComponent()

        # access the document's text property
        text = model.Text

        # create a cursor
        cursor = text.createTextCursor()

        liAddress = self.unpickleObject(id)
        for i in range(0,len(liAddress)):
            # insert the text into the document
            text.insertString( cursor, `liAddress[i]`, 0 )


        # Do a nasty thing before exiting the python process. In case the
        # last call is a oneway call (e.g. see idl-spec of insertString),
        # it must be forced out of the remote-bridge caches before python
        # exits the process. Otherwise, the oneway call may or may not reach
        # the target object.
        # I do this here by calling a cheap synchronous call (getPropertyValue).
        self.ctx.ServiceManager
    def createNewDocument(self, frame, sDocumentType, preview, readonly):
        loadValues = list(range(2))
        loadValues[0] = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
        loadValues[0].Name = "ReadOnly"
        if readonly:
            loadValues[0].Value = True
        else:
            loadValues[0].Value = False

        loadValues[1] = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
        loadValues[1].Name = "Preview"
        if preview:
            loadValues[1].Value = True
        else:
            loadValues[1].Value = False
        sURL = "private:factory/" + sDocumentType
        xComponent = None
        try:
            xComponent = frame.loadComponentFromURL(systemPathToFileUrl(sURL),
                                                    "_self", 0,
                                                    tuple(loadValues))

        except Exception:
            traceback.print_exc()

        return xComponent
    def LoadPresentation(self, file):
        """
        This method opens a file and starts the viewing of it.
        """
        print "LoadPresentation:", file

        # Close existing presentation
        if self.doc:
            if not hasattr(self.doc, "close") :
                self.doc.dispose()
            else:
                self.doc.close(1)

        if not file:
            print "Blank presentation"
            self.doc = self.desktop.loadComponentFromURL("private:factory/simpress","_blank", 0, ()  )
        else:
            if str.startswith(file, "http"):
                print "loading from http"
                self.doc = self.desktop.loadComponentFromURL(file,"_blank", 0, ()  )
            else: 
                self.doc = self.desktop.loadComponentFromURL(unohelper.systemPathToFileUrl(file),"_blank", 0, ()  )

        if not self.doc:
            self.doc = self.desktop.loadComponentFromURL("private:factory/simpress","_blank", 0, ()  )

        self.numPages = self.doc.getDrawPages().getCount()
        self.openFile = file

        # Start viewing the slides in a window
        #self.presentation.SlideShowSettings.ShowType = win32com.client.constants.ppShowTypeWindow
        #self.win = self.presentation.SlideShowSettings.Run()
        self.win = 1
Exemple #36
0
 def actionPerformed(self, actionevent):
     cmd = actionevent.ActionCommand
     if cmd == "filepick":
         systempath = self.editcontrol.getText().strip(
         )  # Editコントロールのテキストを取得。システム固有形式のパスが入っているはず。
         if os.path.exists(systempath):  # パスが実存するとき
             if os.path.isfile(systempath):  # ファイルへのパスであればその親フォルダのパスを取得する。
                 systempath = os.path.dirname(systempath)
             fileurl = unohelper.systemPathToFileUrl(
                 systempath)  # fileurlに変換する。
         else:
             fileurl = self.workurl  # 実存するパスが取得できない時はホームフォルダのfileurlを取得。
         self.filepicker.setDisplayDirectory(
             fileurl)  # 表示するフォルダを設定。設定しないと「最近開いたファイル」が表示される。
         if self.filepicker.execute(
         ) == ExecutableDialogResults_OK:  # ファイル選択ダイアログを表示し、そのOKボタンがクリックされた時。
             fileurl = self.filepicker.getFiles()[
                 0]  # ダイアログで選択されたファイルのパスを取得。fileurlのタプルで返ってくるので先頭の要素を取得。
             if self.simplefileaccess.exists(fileurl):  # fileurlが実存するとき
                 self.imagecontrolmodel.setPropertyValue(
                     "ImageURL", fileurl)  # Imageコントロールに設定。
                 systempath = unohelper.fileUrlToSystemPath(
                     fileurl)  # fileurlをシステム固有形式に変換。
                 self.editcontrol.setText(systempath)  # Editコントロールに表示。
     elif cmd == "close":
         self.frame.close(True)
 def insertImage(self, imagelocation, border=0, width=0, height=0):
     """
     Insert an image object into the document
     
     @param imagelocation: path to image on filesystem
     @type imagelocation: string
     """
     if not os.path.exists(imagelocation):
         raise RuntimeError('Image with location %s does not exist on filesystem' % imagelocation)
     image = Image.open(imagelocation)
     origWidth = image.size[0]
     origHeight = image.size[1]
     if width and not height:
         height = float(origHeight*width)/origWidth
     elif height and not width:
         width = float(height*origWidth)/origHeight
     graph = self.document.createInstance('com.sun.star.text.GraphicObject')
     if border:
         bordersize = int(border) * 26.45833
         graph.LeftBorderDistance = bordersize
         graph.RightBorderDistance = bordersize
         graph.BottomBorderDistance = bordersize
         graph.TopBorderDistance = bordersize
         graph.BorderDistance = bordersize
     if width and height:
         graph.Width = int(width) * 26.45833
         graph.Height = int(height) * 26.45833
     graph.GraphicURL = unohelper.systemPathToFileUrl(imagelocation)
     graph.AnchorType = AS_CHARACTER
     self.document.Text.insertTextContent(self.cursor, graph, False)
Exemple #38
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
Exemple #39
0
def main():  
	ctx = XSCRIPTCONTEXT.getComponentContext()  # コンポーネントコンテクストの取得。
	smgr = ctx.getServiceManager()  # サービスマネージャーの取得。	
	simplefileaccess = smgr.createInstanceWithContext("com.sun.star.ucb.SimpleFileAccess", ctx)  # SimpleFileAccess
	os.chdir("..")  # 一つ上のディレクトリに移動。
	ods = glob.glob("*.ods")[0]  # odsファイルを取得。最初の一つのみ取得。
	systempath = os.path.join(os.getcwd(), ods)  # odsファイルのフルパス。
	doc_fileurl = unohelper.systemPathToFileUrl(systempath)  # fileurlに変換。
	desktop = ctx.getByName('/singletons/com.sun.star.frame.theDesktop')  # デスクトップの取得。
	components = desktop.getComponents()  # ロードしているコンポーネントコレクションを取得。
	transientdocumentsdocumentcontentfactory = smgr.createInstanceWithContext("com.sun.star.frame.TransientDocumentsDocumentContentFactory", ctx)  # TransientDocumentsDocumentContentFactory
	for component in components:  # 各コンポーネントについて。
		if hasattr(component, "getURL"):  # スタートモジュールではgetURL()はないためチェックする。
			if component.getURL()==doc_fileurl:  # fileurlが一致するとき、ドキュメントが開いているということ。
				transientdocumentsdocumentcontent = transientdocumentsdocumentcontentfactory.createDocumentContent(component)
				pkgurl = transientdocumentsdocumentcontent.getIdentifier().getContentIdentifier()  # ex. vnd.sun.star.tdoc:/1
				python_fileurl = "/".join((pkgurl, "Scripts/python"))  # ドキュメント内フォルダへのフルパスを取得。
				if simplefileaccess.exists(python_fileurl):  # 埋め込みマクロフォルダが存在する時。
					dest_dir = createDest(simplefileaccess)  # 出力先フォルダのfileurlを取得。
					simplefileaccess.copy(python_fileurl, dest_dir)  # 埋め込みマクロフォルダを出力先フォルダにコピーする。
					print("The embedded Macro folder in '{}' has been exported to '{}'.".format(python_fileurl, dest_dir))
					return	# 関数を出る。		
	else:  # ドキュメントを開いていない時。
		package = smgr. createInstanceWithArgumentsAndContext("com.sun.star.packages.Package", (doc_fileurl,), ctx)  # Package。第2引数はinitialize()メソッドで後でも渡せる。
		docroot = package.getByHierarchicalName("/")  # /Scripts/pythonは不可。
		if ("Scripts" in docroot and "python" in docroot["Scripts"]):  # 埋め込みマクロフォルダが存在する時。
			dest_dir = createDest(simplefileaccess)  # 出力先フォルダのfileurlを取得。
			getContents(simplefileaccess, docroot["Scripts"]["python"], dest_dir) 
			print("The embedded Macro folder in '{}' has been exported to '{}'.".format(ods, dest_dir))
			return	# 関数を出る。	
	print("The embedded macro folder does not exist in {}.".format(ods))  # 埋め込みマクロフォルダが存在しない時。
Exemple #40
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
Exemple #41
0
 def loadImage(self,image_name,image_file):
     oBitmaps=self.doc.createInstance("com.sun.star.drawing.BitmapTable")
     try:
         oBitmaps.insertByName(image_name,systemPathToFileUrl(image_file))
     except Exception as e:
         print(": > "+e.Message,file=sys.stderr)
     return oBitmaps.getByName(image_name)
Exemple #42
0
    def getResultUrl(self):
        '''Returns the path of the result file in the format needed by OO. If
           the result type and the input type are the same (ie the user wants to
           refresh indexes or some other action and not perform a real
           conversion), the result file is named
                           <inputFileName>.res.<resultType>.

           Else, the result file is named like the input file but with a
           different extension:
                           <inputFileName>.<resultType>
        '''
        import unohelper
        baseName = os.path.splitext(self.docPath)[0]
        if self.resultType != self.inputType:
            res = '%s.%s' % (baseName, self.resultType)
        else:
            res = '%s.res.%s' % (baseName, self.resultType)
        try:
            f = open(res, 'w')
            f.write('Hello')
            f.close()
            os.remove(res)
            return unohelper.systemPathToFileUrl(res)
        except (OSError, IOError), ioe:
            raise ConverterError(CANNOT_WRITE_RESULT % (res, ioe))
Exemple #43
0
    def save(self, fileUrl):
        if not self.doc:
            raise "Failed to save cause there is no document"
        if fileUrl.startswith("file://"):
            fileUrl = fileUrl[7:]
        if not fileUrl:
            raise "Failed to save cause invalid file \"%s\" defined." % fileUrl

        try:
            import unohelper
            outUrl = unohelper.systemPathToFileUrl(fileUrl)
            outProps = []

            fileExt = os.path.splitext(fileUrl)[1].lower()
            if fileExt == '.txt' or fileExt == '.text':
                outProps.append( UnoPropertyValue('FilterName', 0, 'Text (encoded)', 0) )
            elif fileExt == '.htm' or fileExt == '.html':
                outProps.append( UnoPropertyValue('FilterName', 0, 'HTML (StarWriter)', 0) )
            elif fileExt == '.pdf':
                outProps.append( UnoPropertyValue('FilterName', 0, 'writer_pdf_Export', 0) )
            #else: opendocument...

            print "Save to: %s" % outUrl
            self.doc.storeToURL(outUrl, tuple(outProps))
        except:
            traceback.print_exc()
Exemple #44
0
 def insertImage(self, imagelocation, border=0, width=0, height=0):
     """
     Insert an image object into the document
     
     @param imagelocation: path to image on filesystem
     @type imagelocation: string
     """
     if not os.path.exists(imagelocation):
         raise RuntimeError(
             'Image with location %s does not exist on filesystem' %
             imagelocation)
     image = Image.open(imagelocation)
     origWidth = image.size[0]
     origHeight = image.size[1]
     if width and not height:
         height = float(origHeight * width) / origWidth
     elif height and not width:
         width = float(height * origWidth) / origHeight
     graph = self.document.createInstance('com.sun.star.text.GraphicObject')
     if border:
         bordersize = int(border) * 26.45833
         graph.LeftBorderDistance = bordersize
         graph.RightBorderDistance = bordersize
         graph.BottomBorderDistance = bordersize
         graph.TopBorderDistance = bordersize
         graph.BorderDistance = bordersize
     if width and height:
         graph.Width = int(width) * 26.45833
         graph.Height = int(height) * 26.45833
     graph.GraphicURL = unohelper.systemPathToFileUrl(imagelocation)
     graph.AnchorType = AS_CHARACTER
     self.document.Text.insertTextContent(self.cursor, graph, False)
Exemple #45
0
 def loadDoc(self,name):
     """ Load a document
     @param name Document filename
     """
     # get the file name of the document
     if list(self.docList.keys()).count(name)>0:
         self.doc=self.docList[name][0]
         self.format=self.docList[name][1]
     else:
         addressDoc=systemPathToFileUrl(name)
         if self.filterOptions is not None:
             tmp=name.split('/')
             tmp=tmp[len(tmp)-1].split('.')
             print(tmp,file=sys.stderr)
             propFich=(
                 PropertyValue("Hidden", 0, True, 0),
                 PropertyValue("FilterName", 0, self.outputFormat["ODS"][tmp[len(tmp)-1].lower()][1], 0),
                 PropertyValue("FilterOptions", 0, self.filterOptions, 0),
                 )
         else:
             propFich=PropertyValue("Hidden", 0, True, 0),
         doc=0
         try:
             self.doc=self.desktop.loadComponentFromURL(addressDoc,"_blank",0,propFich)
             #print(self.doc,file=sys.stderr)
             tmp=name.split('/')
             self.format=tmp[len(tmp)-1].split('.')[1].upper()
             self.docList[name]=[self.doc,self.format,addressDoc]
         except Exception as e:
             print('Unable to open the file for the following reasons:\n'+str(e),file=sys.stderr)
             return None
    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
Exemple #47
0
 def load_file(self, doc, doc_file_id, path):
     document = self.desktop.loadComponentFromURL(unohelper.systemPathToFileUrl(path),
                                                  "_default", 0, ())
     if not document:
         # document may be a simple text file
         op1 = PropertyValue()
         op1.Name = 'InteractionHandler'
         op1.Value = self.smgr.createInstance("com.sun.star.task.InteractionHandler") 
         document = self.desktop.loadComponentFromURL(unohelper.systemPathToFileUrl(path),
             "_default", 0, (op1,))
     if not document:
         show_error("Can not load %s" % path, self.window)
         return
     self.documents[document.URL] = dict(openplm_doc=doc,
         openplm_file_id=doc_file_id, openplm_path=path)
     document.setTitle(document.getTitle() + " / %(name)s rev. %(revision)s" % doc)
     return document
Exemple #48
0
def main(host, port, path, pagecountlimit):
    retVal = 0
    pagecountlimit = '50'
    doc = None

    url = "uno:socket,host=%s,port=%d;urp;StarOffice.ComponentContext" % (host, port)

    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, "StarOffice XML (Writer)" , 0 ),
        PropertyValue( "OutputStream",0, OutputStream(),0),)
    inProps = (PropertyValue( "Hidden" , 0 , True, 0 ),)
    try:
        fileUrl = uno.absolutize( cwd, systemPathToFileUrl(path) )
        doc = desktop.loadComponentFromURL( fileUrl, "_blank", 0, inProps)

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

        # pdb.set_trace()

        try:
            cursor = doc.getCurrentController().getViewCursor()
            cursor.jumpToLastPage()
            pagecount = cursor.getPage()
            if pagecount > int(pagecountlimit):
                raise UnoException( "Input document has %d pages which exceeeds the page count limit of %d." % (pagecount, int(pagecountlimit)), None )
        except  AttributeError:
             # opened picture files will not behave, but do not need to have their page counted
             pass

        doc.storeToURL("private:stream",outProps)
    except IOException, e:
        sys.stderr.write( "Error during conversion: " + e.Message + "\n" )
        retVal = 1
Exemple #49
0
def Xml2Pdf(conf,input,output):
    localContext = uno.getComponentContext()
    resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
    ctx = resolver.resolve( "uno:socket,host=127.0.0.1,port=3662;urp;StarOffice.ComponentContext" )
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
    adressDoc=systemPathToFileUrl(input["doc"]["value"])
    propFich=PropertyValue("Hidden", 0, True, 0),
    try:
        myDocument = desktop.loadComponentFromURL(adressDoc,"_blank",0,propFich)
	#Prefer to create a new document without any style ?
        #myDocument = desktop.loadComponentFromURL("private:factory/writer","_blank",0,propFich)
    except:
        conf["lenv"]["message"]='Unable to load input document'
	return 4
    text = myDocument.Text
    cursor = text.createTextCursor()
    cursor.gotoStart(0)
    cursor.gotoEnd(1)
    xmldoc = minidom.parseString(input['xml']['value'])

    if xmldoc.hasChildNodes():
        for i in xmldoc.childNodes:
            if i.nodeType==1:
                cursor.ParaStyleName="Title"
                text.insertString( cursor, i.nodeName , 0 )
                text.insertControlCharacter( cursor, PARAGRAPH_BREAK , 0 )
                #print >> sys.stderr,' * 1st level' + i.nodeName
                if i.hasChildNodes():
                    for j in i.childNodes:
                        printChildren(cursor,text,j,2,'')

    tmp=myDocument.StyleFamilies.getByName("NumberingStyles")

    tmp1=tmp.getByName("Puce 1")

    prop1Fich = ( PropertyValue( "FilterName" , 0, "writer_pdf_Export", 0 ),PropertyValue( "Overwrite" , 0, True , 0 ) )
    outputDoc=systemPathToFileUrl("/tmp/output.pdf")
    myDocument.storeToURL(outputDoc,prop1Fich)

    myDocument.close(True)
    ctx.ServiceManager
    output["Document"]["value"]= open('/tmp/output.pdf', 'r').read()
    print >> sys.stderr,len(output["Document"]["value"])
    return 3
 def loadExsitingDocument(self, doclocation):
     """
     Load an existing document from the filesystem
     """
     if not os.path.exists(doclocation):
         raise RuntimeError('Document with location %s does not exist on the filesystem' % doclocation)
     url = unohelper.systemPathToFileUrl(doclocation)
     self.document = self.desktop.loadComponentFromURL(url, "_blank", 0, ())
     return self.document
Exemple #51
0
 def getInputUrls(self, docPath):
     '''Returns the absolute path of the input file. In fact, it returns a
        tuple with some URL version of the path for OO as the first element
        and the absolute path as the second element.''' 
     import unohelper
     if not os.path.exists(docPath) and not os.path.isfile(docPath):
         raise ConverterError(DOC_NOT_FOUND % docPath)
     docAbsPath = os.path.abspath(docPath)
     # Return one path for OO, one path for me.
     return unohelper.systemPathToFileUrl(docAbsPath), docAbsPath
Exemple #52
0
 def getInputUrls(self, docPath):
     '''Returns the absolute path of the input file. In fact, it returns a
        tuple with some URL version of the path for OO as the first element
        and the absolute path as the second element.''' 
     import unohelper
     if not os.path.exists(docPath) and not os.path.isfile(docPath):
         raise ConverterError(DOC_NOT_FOUND % docPath)
     docAbsPath = os.path.abspath(docPath)
     # Return one path for OO, one path for me.
     return unohelper.systemPathToFileUrl(docAbsPath), docAbsPath
Exemple #53
0
def export2pdf(ooo_info,dest_file):
    """
    """
    from unohelper import systemPathToFileUrl
    dest_url = systemPathToFileUrl(dest_file)
    print "save as pdf from %s"%(dest_file)
    pp_filter = PropertyValue()
    pp_filter.Name = "FilterName"
    pp_filter.Value = "writer_pdf_Export"
    outprop = (pp_filter, PropertyValue( "Overwrite" , 0, True , 0 ),)
    ooo_info['doc'].storeToURL(dest_url, outprop)
Exemple #54
0
 def loadExsitingDocument(self, doclocation):
     """
     Load an existing document from the filesystem
     """
     if not os.path.exists(doclocation):
         raise RuntimeError(
             'Document with location %s does not exist on the filesystem' %
             doclocation)
     url = unohelper.systemPathToFileUrl(doclocation)
     self.document = self.desktop.loadComponentFromURL(url, "_blank", 0, ())
     return self.document
Exemple #55
0
    def load(self, xInterface, sURL, sFrame, xValues):
        xComponent = None
        try:
            if not sURL.startswith("file://"):
                sURL = systemPathToFileUrl(sURL)
            xComponent = xInterface.loadComponentFromURL(
                sURL, sFrame, 0, tuple(xValues))
        except Exception:
            traceback.print_exc()

        return xComponent
    def load(self, xInterface, sURL, sFrame, xValues):
        xComponent = None
        try:
            if not sURL.startswith("file://"):
                sURL = systemPathToFileUrl(sURL)
            xComponent = xInterface.loadComponentFromURL(
                sURL, sFrame, 0, tuple(xValues))
        except Exception:
            traceback.print_exc()

        return xComponent
Exemple #57
0
 def load_file(self, doc, doc_file_id, path):
     document = self.desktop.loadComponentFromURL(
         unohelper.systemPathToFileUrl(path), "_default", 0, ())
     if not document:
         # document may be a simple text file
         op1 = PropertyValue()
         op1.Name = 'InteractionHandler'
         op1.Value = self.smgr.createInstance(
             "com.sun.star.task.InteractionHandler")
         document = self.desktop.loadComponentFromURL(
             unohelper.systemPathToFileUrl(path), "_default", 0, (op1, ))
     if not document:
         show_error("Can not load %s" % path, self.window)
         return
     self.documents[document.URL] = dict(openplm_doc=doc,
                                         openplm_file_id=doc_file_id,
                                         openplm_path=path)
     document.setTitle(document.getTitle() +
                       " / %(name)s rev. %(revision)s" % doc)
     return document
Exemple #58
0
 def appendDoc(self,name):
     """ Append a document to the current document
     @param name Document to append filename
     """
     if self.cursor is None:
         self.getCursor()
     self.cursor.gotoEnd(0)
     self.cursor.BreakType = PAGE_BEFORE
     self.text.insertControlCharacter( self.cursor, PARAGRAPH_BREAK , 0 )
     aDoc=systemPathToFileUrl(name)
     self.cursor.insertDocumentFromURL(aDoc, ())