示例#1
0
def uno_save(document, filename, type):
    """ Save document
    document: desktop.loadComponentFromURL
    filename: filename of output without ext
    type: extension, example odt
    """
    from com.sun.star.beans import PropertyValue
    tmp = tempfile.NamedTemporaryFile()

    # Strictly sanitize filename since Content-Disposition is really fussy
    filename = re.sub(
        '[^A-Za-z0-9]+',
        '_',
        strip_unicode_to_ascii(filename)
    )
    if type == "doc":
        properties = (
            PropertyValue("Overwrite",0,True,0),
            PropertyValue("FilterName",0,"MS Word 97",0))
        document.storeToURL("file://" + str(tmp.name), properties)
        content = "application/msword"
        filename += ".doc"
    if type == "docx":
        properties = (
            PropertyValue("Overwrite",0,True,0),
            PropertyValue("FilterName",0,"MS Word 2007 XML",0))
        document.storeToURL("file://" + str(tmp.name), properties)
        content = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        filename += ".docx"
    elif type == "pdf":
        properties = (
            PropertyValue("Overwrite",0,True,0),
            PropertyValue("FilterName",0,"writer_pdf_Export",0))
        document.storeToURL("file://" + str(tmp.name), properties)
        content = "application/pdf"
        filename += ".pdf"
    elif type == "ods":
        document.storeToURL("file://" + str(tmp.name), ())
        content = "application/vnd.oasis.opendocument.spreadsheet"
        filename += ".ods"
    elif type == "xlsx":
        properties = (
            PropertyValue("Overwrite",0,True,0),
            PropertyValue("FilterName",0,"Calc MS Excel 2007 XML",0))
        document.storeToURL("file://" + str(tmp.name), properties)
        content = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        filename += ".xlsx"
    elif type == "xls":
        properties = (
            PropertyValue("Overwrite",0,True,0),
            PropertyValue("FilterName",0,"MS Excel 97",0))
        document.storeToURL("file://" + str(tmp.name), properties)
        content = "application/vnd.ms-excel"
        filename += ".xls"
    else:
        document.storeToURL("file://" + str(tmp.name), ())
        content = "application/vnd.oasis.opendocument.text"
        filename += ".odt"
    document.close(True)
    return tmp, filename, content
示例#2
0
 def test_numberRecognition(self):
     xDoc = CheckTable._uno.openEmptyWriterDoc()
     xDocFrame = xDoc.CurrentController.Frame
     xContext = CheckTable._uno.getContext()
     xServiceManager = xContext.ServiceManager
     xDispatcher = xServiceManager.createInstanceWithContext(
         'com.sun.star.frame.DispatchHelper', xContext)
     xTable = xDoc.createInstance('com.sun.star.text.TextTable')
     xTable.initialize(2, 1)
     xCursor = xDoc.Text.createTextCursor()
     xDoc.Text.insertTextContent(xCursor, xTable, False)
     xDispatcher.executeDispatch(xDocFrame, '.uno:GoToStartOfDoc', '', 0, ())
     xDispatcher.executeDispatch(xDocFrame, '.uno:InsertText', '', 0,
                                 (PropertyValue('Text', 0, '2015-10-30', 0),))
     xDispatcher.executeDispatch(xDocFrame, '.uno:JumpToNextCell', '', 0, ())
     # Without number recognition 2015-10-30 should not be interpreted as a date
     self.assertEqual(xTable[0,0].getString(), '2015-10-30')
     self.assertEqual(xTable[0,0].getValue(), 0)
     # Activate number recognition
     xDispatcher.executeDispatch(xDocFrame, '.uno:TableNumberRecognition', '', 0,
                                 (PropertyValue('TableNumberRecognition', 0, True, 0),))
     xDispatcher.executeDispatch(xDocFrame, '.uno:InsertText', '', 0,
                                 (PropertyValue('Text', 0, '2015-10-30', 0),))
     xDispatcher.executeDispatch(xDocFrame, '.uno:JumpToNextCell', '', 0, ())
     # With number recognition it should now be a date, confirm by checking
     # the string and value of the cell.
     self.assertEqual(xTable[1,0].getString(), '2015-10-30')
     self.assertEqual(xTable[1,0].getValue(), 42307.0)
     xDoc.dispose()
示例#3
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
示例#4
0
    def testCustomProperties(self):
        uiComponent = self.ui_test._xContext.ServiceManager.createInstanceWithContext(
            "com.sun.star.comp.Writer.EPUBExportUIComponent",
            self.ui_test._xContext)

        # Make sure that by default the version is not altered.
        propertyValues = uiComponent.getPropertyValues()
        filterData = [
            i.Value for i in propertyValues if i.Name == "FilterData"
        ][0]
        self.assertEqual(
            0, len([i.Value for i in filterData if i.Name == "EPUBVersion"]))

        # But if we set it explicitly, then it's retained, even without interacting with the UI.
        filterData = (PropertyValue(Name="EPUBVersion", Value=30), )
        propertyValues = (PropertyValue(
            Name="FilterData",
            Value=uno.Any("[]com.sun.star.beans.PropertyValue", filterData)), )
        uiComponent.setPropertyValues(propertyValues)
        propertyValues = uiComponent.getPropertyValues()
        filterData = [
            i.Value for i in propertyValues if i.Name == "FilterData"
        ][0]
        epubVersion = [i.Value for i in filterData
                       if i.Name == "EPUBVersion"][0]
        self.assertEqual(30, epubVersion)
示例#5
0
    def export_active_sheet_to_pdf(self, dest: 'path_to_pdf_file'):
        """notes: assuming the area of the active sheet to be printed is
    'a1:h30'
    """

        active_sheet = self.model.getCurrentController().getActiveSheet()

        # have to select the area to be printed
        fdata = []
        fdata1 = PropertyValue()
        fdata1.Name = 'Selection'
        oCellRange = active_sheet.getCellRangeByName('a1:h30')
        fdata1.Value = oCellRange
        fdata.append(fdata1)

        args = []
        arg1 = PropertyValue()
        arg1.Name = 'FilterName'
        arg1.Value = 'calc_pdf_Export'
        arg2 = PropertyValue()
        arg2.Name = 'FilterData'
        arg2.Value = uno.Any("[]com.sun.star.beans.PropertyValue",
                             tuple(fdata))
        args.append(arg1)
        args.append(arg2)

        self.model.storeToURL('file:///' + dest, tuple(args))
示例#6
0
def do_file(file, desktop, destination):
    file_l = file.lower()

    global format
    if extension == "html":
        if file_l.endswith(".xls"):
            format = "HTML (StarCalc)"
        elif file_l.endswith(".doc") or file_l.endswith(".wpd"):
            # doc: MS Office Word
            # wpd: Corel WP
            format = "HTML (StarWriter)"
        else:
            print "%s: unkown extension" % file
            return

    assert (format)
    assert (extension)
    assert (destination)

    file_save = "%s.%s" % (destination, extension)
    file_save = os.path.abspath(file_save)

    properties = []
    p = PropertyValue()
    p.Name = "Hidden"
    p.Value = True
    properties.append(p)

    doc = desktop.loadComponentFromURL("file://%s" % file, "_blank", 0,
                                       tuple(properties))
    if not doc:
        print "Failed to open '%s'" % file
        return
    # Save File
    properties = []
    p = PropertyValue()
    p.Name = "Overwrite"
    p.Value = True
    properties.append(p)
    p = PropertyValue()
    p.Name = "FilterName"
    p.Value = format
    properties.append(p)
    p = PropertyValue()
    p.Name = "Hidden"
    p.Value = True
    try:
        doc.storeToURL("file://%s" % file_save, tuple(properties))
        print "Created %s" % file_save
    except ValueError:
        import sys
        import traceback
        import cStringIO
        (exc_type, exc_value, tb) = sys.exc_info()
        error_file = cStringIO.StringIO()
        traceback.print_exception(exc_type, exc_value, tb, file=error_file)
        stacktrace = error_file.getvalue()
        print "Failed while writing: '%s'" % file_save
        print stacktrace
    doc.dispose()
 def _createErrorForWriter(self, nStart, nLen, sRuleId, sOption, sMessage,
                           lSugg, sURL):
     xErr = SingleProofreadingError(
     )  # uno.createUnoStruct( "com.sun.star.linguistic2.SingleProofreadingError" )
     xErr.nErrorStart = nStart
     xErr.nErrorLength = nLen
     xErr.nErrorType = PROOFREADING
     xErr.aRuleIdentifier = sRuleId
     xErr.aShortComment = sMessage  # sMessage.split("|")[0]     # in context menu
     xErr.aFullComment = sMessage  # sMessage.split("|")[-1]    # in dialog
     xErr.aSuggestions = tuple(lSugg)
     # Properties
     lProperties = []
     if _nUnderliningStyle:
         lProperties.append(
             PropertyValue(Name="LineType", Value=_nUnderliningStyle))
     if _bMulticolor:
         lProperties.append(
             PropertyValue(Name="LineColor",
                           Value=_dOptionsColors.get(sOption, 33023)))
     if sURL:
         lProperties.append(PropertyValue(Name="FullCommentURL",
                                          Value=sURL))
     xErr.aProperties = lProperties
     return xErr
示例#8
0
 def loadDocument(self):
     from com.sun.star.lang import IllegalArgumentException, \
                                   IndexOutOfBoundsException
     from com.sun.star.beans import PropertyValue
     try:
         # Loads the document to convert in a new hidden frame
         prop = PropertyValue(); prop.Name = 'Hidden'; prop.Value = True
         if self.inputType == 'csv':
             prop2 = PropertyValue()
             prop2.Name = 'FilterFlags'
             prop2.Value = '59,34,76,1'
             #prop2.Name = 'FilterData'
             #prop2.Value = 'Any'
             props = (prop, prop2)
         else:
             props = (prop,)
         # Give some additional params if we need to open a CSV file
         self.doc = self.oo.loadComponentFromURL(self.docUrl, "_blank", 0,
                                                 props)
         if self.inputType == 'odt':
             # Perform additional tasks for odt documents
             self.updateOdtDocument()
         try:
             self.doc.refresh()
         except AttributeError:
             pass
     except IllegalArgumentException, iae:
         raise ConverterError(URL_NOT_FOUND % (self.docPath, iae))
示例#9
0
 def createHiddenWindow(self, url):
     service_manager = self.context.ServiceManager
     desktop = service_manager.createInstanceWithContext(
         'com.sun.star.frame.Desktop', self.context)
     load_props = (PropertyValue(Name='Hidden', Value=True),
                   PropertyValue(Name='ReadOnly', Value=False))
     component = desktop.loadComponentFromURL(url, '_blank', 0, load_props)
     return component
示例#10
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
示例#11
0
 def test_render_property_value(self):
     expected = 'Nombre: Teresa\nPaís: Portugal'
     template = 'Nombre: $name\nPaís: $country'
     data = (
         PropertyValue('name', -1, 'Teresa', 1),
         PropertyValue('country', -1, 'Portugal', 1),
     )
     result = self.tools.render(template, data)
     self.assertEqual(result, expected)
示例#12
0
 def toProperties(self, propDict):
     properties = []
     for key in propDict:
         if type(propDict[key]) == dict:
             prop = PropertyValue(key, 0, uno.Any("[]com.sun.star.beans.PropertyValue",self.toProperties(propDict[key])), 0)
         else:
             prop = PropertyValue(key, 0, propDict[key], 0)
         properties.append(prop)
     return tuple(properties)
示例#13
0
 def apply_style_to_orphan_timecode(self):
     # method by regex
     bold = PropertyValue('CharWeight', 0, FontWeight.BOLD, 0)
     color = PropertyValue('CharColor', 0, 6710932, 0)
     rd = self.doc.createReplaceDescriptor()
     rd.SearchRegularExpression = True
     rd.SearchString = '^\s?(\[\d{2}:\d{2}:\d{2}(.\d+)?\])\s?$'
     rd.setReplaceAttributes((bold, color))
     rd.ReplaceString = "$1"
     self.doc.replaceAll(rd)
示例#14
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 _toProperties(self, options):
     import uno
     from com.sun.star.beans import PropertyValue
     props = []
     for key in options:
         if isinstance(options[key], dict):
             prop = PropertyValue(key, 0, uno.Any("[]com.sun.star.beans.PropertyValue",
                                                  (self._toProperties(options[key]))), 0)
         else:
             prop = PropertyValue(key, 0, options[key], 0)
         props.append(prop)
     return tuple(props)
示例#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 test_setArgs_valid(self):
        xDoc = self._uno.openEmptyWriterDoc()
        self.assertIsNotNone(xDoc)

        p1 = PropertyValue(Name="SuggestedSaveAsName", Value="prettyFileName")
        p2 = PropertyValue(Name="SuggestedSaveAsDir", Value="/my/dir")
        p3 = PropertyValue(Name="LockContentExtraction", Value=True)
        p4 = PropertyValue(Name="LockExport", Value=True)
        p5 = PropertyValue(Name="LockPrint", Value=True)
        p6 = PropertyValue(Name="LockSave", Value=True)
        p7 = PropertyValue(Name="LockEditDoc", Value=True)
        p8 = PropertyValue(Name="Replaceable", Value=True)
        xDoc.setArgs([p1, p2, p3, p4, p5, p6, p7, p8])

        # Make sure that all properties are returned with getArgs()
        args = xDoc.getArgs()
        self.assertTrue(p1 in args)
        self.assertTrue(p2 in args)
        self.assertTrue(p3 in args)
        self.assertTrue(p4 in args)
        self.assertTrue(p5 in args)
        self.assertTrue(p6 in args)
        self.assertTrue(p7 in args)
        self.assertTrue(p8 in args)

        xDoc.close(True)
示例#18
0
    def test_setArgs_valid(self):
        xDoc = self._uno.openEmptyWriterDoc()
        self.assertIsNotNone(xDoc)

        p1 = PropertyValue(Name="SuggestedSaveAsName", Value="prettyFileName")
        p2 = PropertyValue(Name="SuggestedSaveAsDir", Value="/my/dir")
        xDoc.setArgs([p1, p2])

        # Make sure that all properties are returned with getArgs()
        args = xDoc.getArgs()
        self.assertTrue(p1 in args)
        self.assertTrue(p2 in args)

        xDoc.close(True)
    def test_checkIndexedPropertyValues(self):

        xServiceManager = self.xContext.ServiceManager
        xCont = xServiceManager.createInstanceWithContext(
            'com.sun.star.document.IndexedPropertyValues', self.xContext)

        p1 = PropertyValue(Name="Jupp", Value="GoodGuy")
        prop1 = uno.Any("[]com.sun.star.beans.PropertyValue", (p1, ))

        p2 = PropertyValue(Name="Horst", Value="BadGuy")
        prop2 = uno.Any("[]com.sun.star.beans.PropertyValue", (p2, ))

        p3 = PropertyValue(Name="Peter", Value="FamilyGuy")
        prop3 = uno.Any("[]com.sun.star.beans.PropertyValue", (p3, ))

        t = xCont.getElementType()
        self.assertEqual(0, xCont.getCount(), "Initial container is not empty")
        uno.invoke(xCont, "insertByIndex", (0, prop1))

        ret = xCont.getByIndex(0)
        self.assertEqual(p1.Name, ret[0].Name)
        self.assertEqual(p1.Value, ret[0].Value)

        uno.invoke(xCont, "replaceByIndex", (0, prop2))
        ret = xCont.getByIndex(0)
        self.assertEqual(p2.Name, ret[0].Name)
        self.assertEqual(p2.Value, ret[0].Value)

        xCont.removeByIndex(0)
        self.assertTrue(not (xCont.hasElements()) and xCont.getCount() == 0,
                        "Could not remove PropertyValue")
        uno.invoke(xCont, "insertByIndex", (0, prop1))
        uno.invoke(xCont, "insertByIndex", (1, prop2))
        self.assertTrue(xCont.hasElements() and xCont.getCount() == 2,
                        "Did not insert PropertyValue")

        uno.invoke(xCont, "insertByIndex", (1, prop2))
        uno.invoke(xCont, "insertByIndex", (1, prop3))
        ret = xCont.getByIndex(1)
        self.assertEqual(p3.Name, ret[0].Name)
        self.assertEqual(p3.Value, ret[0].Value)

        with self.assertRaises(IndexOutOfBoundsException):
            uno.invoke(xCont, "insertByIndex", (25, prop2))

        with self.assertRaises(IndexOutOfBoundsException):
            xCont.removeByIndex(25)

        with self.assertRaises(IllegalArgumentException):
            uno.invoke(xCont, "insertByIndex", (3, "Example String"))
示例#20
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
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
示例#22
0
class OOConverter:
    """
    Convert documents by means of Open Office.
    """
    
    def __init__(self, desktop):
        self.desktop = desktop

    def convert(self, fromFile, toFile, format):
        """
        fromFile -- source file name
        toFile   -- destination file name
        format   -- instance of Format class
        """
        desktop = self.desktop
        fromFile=os.path.abspath(fromFile)
        url="file://%s" % fromFile
        properties=[]
        p=PropertyValue()
        p.Name="Hidden"
        p.Value=True
        properties.append(p)
        doc=desktop.loadComponentFromURL(
            url, "_blank", 0, tuple(properties));
        if not doc:
            print "Failed to open '%s'" % file
            return False
        # Save File
        properties=[]
        p=PropertyValue()
        p.Name="Overwrite"
        p.Value=True
        properties.append(p)
        p=PropertyValue()
        p.Name="FilterName"
        p.Value=format.filterName
        properties.append(p)
        p=PropertyValue()
        p.Name="Hidden"
        p.Value=True
        url_save="file://%s" % os.path.abspath(toFile)
        try:
            doc.storeToURL(
                url_save, tuple(properties))
        except:
            print "Failed while writing: '%s'" % file
        doc.dispose()
        return True
示例#23
0
 def convert2pdf(self):
     starttime = time.time() * 1000
     outproperties = (
         PropertyValue( "FilterName" , 0, self.export_format , 0 ),
         PropertyValue( "Overwrite" , 0, True , 0 ),
         PropertyValue( "Hidden",0, True,0))
     #save files
     try:
         self.doc.storeToURL(self.url_output, outproperties)
         endtime = time.time() * 1000
         
         print endtime - starttime
     except:
         print "Error !!!"
     finally:
         self.doc.dispose()
示例#24
0
    def saveByStream(self, filter_name=None):
        """
        Downloads document from office service
        """
        self._updateDocument()
        outputStream = OutputStreamWrapper(False)
        properties = {"OutputStream": outputStream}
        properties.update({"FilterName": filter_name})
        if filter_name == 'Text - txt - csv (StarCalc)':
            properties.update({"FilterOptions": CSVFilterOptions})
        props = self._toProperties(**properties)
        # PDF/A format # TODO: make it configurable from client side
        if filter_name == 'writer_pdf_Export':
            props += (PropertyValue(
                "FilterData", 0,
                uno.Any(
                    "[]com.sun.star.beans.PropertyValue",
                    self._toProperties(SelectPdfVersion=1),
                ), 0), )

        try:
            #url = uno.systemPathToFileUrl(path) #when storing to filesystem
            self.document.storeToURL('private:stream', props)
        except Exception as exception:
            exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
            traceback.print_exception(exceptionType,
                                      exceptionValue,
                                      exceptionTraceback,
                                      limit=2,
                                      file=sys.stdout)
        openDocumentBytes = outputStream.data.getvalue()
        outputStream.close()
        return openDocumentBytes
示例#25
0
 def _createProperty(self, name, value):
     """Create property"""
     from com.sun.star.beans import PropertyValue
     property = PropertyValue()
     property.Name = name
     property.Value = value
     return property
    def tstDoc(self):
        try:
            props = [("ReadOnly", True)]
            loadProps = tuple([self.mkPropertyValue(name, value) for (name, value) in props])

            m_xMSF = self.xContext.ServiceManager
            desktop = m_xMSF.createInstanceWithContext('com.sun.star.frame.Desktop', self.xContext)

            filepath = os.path.abspath("FIXME")
            if os.name == "nt":
                sourceFile = "file:///" + filepath + "/" + quote(self.fileName)
            else:
                sourceFile = "file://" + quote(filepath) + "/" + quote(self.fileName)
            self.xDoc = desktop.loadComponentFromURL(sourceFile, "_blank", 0, loadProps)
            assert(self.xDoc)

            if os.name == "nt":
                targetFile = "file:///" + self.m_TargetDir + quote(self.m_SourceDir) + "/" + quote(self.fileName)
            else:
                targetFile = "file://" +
                            quote(self.m_TargetDir) +
                            quote(self.m_SourceDir) +
                            "/" +
                            quote(self.fileName)

            p1 = PropertyValue()
            PropValue = uno.Any("[]com.sun.star.beans.PropertyValue", (p1,))
            uno.invoke(self.xDoc, "storeToURL", (targetFile, PropValue))
示例#27
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
示例#28
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))  # 各コントロールに値を入力する。		
示例#29
0
def getLanguage():
    """
    Get current user interface language in string format. Useful for
    UI locale checkong on l10n operations (e.g. gettext...) 
    """

    oProvider = "com.sun.star.configuration.ConfigurationProvider"
    oAccess = "com.sun.star.configuration.ConfigurationAccess"
    oConfigProvider = get_instance(oProvider)
    oProp = PropertyValue()
    oProp.Name = "nodepath"
    oProp.Value = "org.openoffice.Office.Linguistic/General"
    properties = (oProp, )
    key = "UILocale"
    oSet = oConfigProvider.createInstanceWithArguments(oAccess, properties)
    if oSet and (oSet.hasByName(key)):
        ooLang = oSet.getPropertyValue(key)

    if not (ooLang and not ooLang.isspace()):
        oProp.Value = "/org.openoffice.Setup/L10N"
        properties = (oProp, )
        key = "ooLocale"
        oSet = oConfigProvider.createInstanceWithArguments(oAccess, properties)
        if oSet and (oSet.hasByName(key)):
            ooLang = oSet.getPropertyValue(key)
    return ooLang
示例#30
0
    def __getGraphic(self, sImageUrl):
        """Returns the xGraphic object from the
            given image location

        Arguments:
        - `sImageUrl`:String
        """
        xGraphic = None

        try:

            #create a GraphicProvider at the global service manager...
            oGraphicProvider = self.xMultiComponentFactory.\
              createInstanceWithContext(
                    "com.sun.star.graphic.GraphicProvider", self.m_xContext)
            aPropertyValue = PropertyValue()
            aPropertyValue.Name = "URL"
            aPropertyValue.Value = sImageUrl
            #Create an array
            #aPropertyValues=()
            aPropertyValues = (aPropertyValue, )

            xGraphic = oGraphicProvider.queryGraphic(aPropertyValues)

            return xGraphic

        except Exception, ex:
            print 'Exception in LicenseChooserDialog.__getGraphic'
            traceback.print_exc()
            raise ex