def __init__(self, ctx, part1=[], selection_cb=None, title='MySearch'): self.ctx = ctx self.desktop = self.ctx.ServiceManager.createInstanceWithContext('com.sun.star.frame.Desktop', self.ctx) self.doc = self.desktop.getCurrentComponent() self.ctrl = self.doc.getCurrentController() self.smgr = self.ctx.getServiceManager() self.parent = self.desktop.getCurrentFrame().getContainerWindow() self.toolkit = self.parent.getToolkit() if self.get_sheet().Name == 'Labels': return if not hasattr(self, 'x'): self.x = 100 self.y = 100 self.w = 200 self.h = 300 pv = PropertyValue() pv.Name = 'nodepath' pv.Value = 'vnd.myparts.settings/%s' % title.lower() self.pv = pv self.config_read() self.title = title self.init_dlg() if title != 'MySearch': return self.result = OD() if part1: self.part_search(None, part1) self.display_results(part1) self.selection_cb = selection_cb
def create_document(title="Untitled", short_summary="", teaser="", story="", locations="", people="", companies="", keywords="", language=""): doc = locals().copy() 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) document = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, ()) doc_properties = PropertyValue() doc_properties.Name = "FilterName" doc_properties.Value = "MS Word 97" text = document.Text cursor = text.createTextCursor() sections = """title short_summary teaser story locations people companies keywords language""".split() for section in sections: if doc.get(section): input_ = "%s: %s" % (section.capitalize(), doc[section]) text.insertString(cursor, input_, 0) text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0) output = "file://%s" % filename() document.storeAsURL(output, (doc_properties,)) document.dispose() return output[7:]
def openFile(self): service_manager, desktop = _uno_init() rows = [] try: # load the Document # load it hidden, see http://www.sethanil.com/python-for-friends/5 p=PropertyValue() p.Name = 'Hidden' p.Value = True properties=(p,) document = desktop.loadComponentFromURL(self.fileName, "_blank", 0, properties) #document = desktop.loadComponentFromURL(self.fileName, "_blank", 0, ()) controller = document.getCurrentController() sheets = document.getSheets() #print 'found %d sheets'% sheets.getCount() ## iterate on all the spreadsheets in the document #enumeration = sheets.createEnumeration() #while enumeration.hasMoreElements(): # sheet = enumeration.nextElement() # name = sheet.getName() # print "sheet: %s " % name enumeration = sheets.createEnumeration() sheet = enumeration.nextElement() # http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/Star_OpenOffice/StarOffice_Calc/Q_26238468.html # determining the used area cursor = sheet.createCursor() cursor.gotoStartOfUsedArea(False) cursor.gotoEndOfUsedArea(True) rangeaddress = cursor.getRangeAddress() rows = cursor.getDataArray() except Exception: print "Unexpected error:", sys.exc_info()[0] finally: document.close(True) return rows
def test_chartdataprovider(self): xDoc = CheckTable._uno.openEmptyWriterDoc() xTable = xDoc.createInstance("com.sun.star.text.TextTable") xTable.initialize(4, 3) xCursor = xDoc.Text.createTextCursor() xDoc.Text.insertTextContent(xCursor, xTable, False) xTable.ChartColumnAsLabel = False xTable.ChartRowAsLabel = False xTable.Data = ((1,2,3), (4,5,6), (7,8,9), (10,11,12)) self.assertTrue(xTable.Name == 'Table1') self.assertIn('com.sun.star.text.GenericTextDocument', xDoc.SupportedServiceNames) xChartdataprovider = xDoc.createInstance('com.sun.star.chart2.data.DataProvider') self.assertIs(type(xChartdataprovider.ImplementationName), type('SwChartDataProvider')) # not testing value, just type and coverage self.assertTrue(xChartdataprovider.supportsService('com.sun.star.chart2.data.DataProvider')) self.assertFalse(xChartdataprovider.supportsService('foo')) self.assertIn('com.sun.star.chart2.data.DataProvider', xChartdataprovider.SupportedServiceNames) pv = PropertyValue() pv.Name = 'CellRangeRepresentation' pv.Value = 'Table1.A1:C2' xDataSource = xChartdataprovider.createDataSource((pv,)) self.assertEqual(len(xDataSource.DataSequences), 3) expectedValues = ((1,4), (2,5), (3,6)) expectedCellrange = ('A1:A2', 'B1:B2', 'C1:C2') for col in range(3): xSeq = xDataSource.DataSequences[col].Values self.assertIs(type(xSeq.ImplementationName), type('SwChartDataSequence')) # not testing value, just type and coverage self.assertTrue(xSeq.supportsService('com.sun.star.chart2.data.DataSequence')) self.assertFalse(xSeq.supportsService('foo')) self.assertIn('com.sun.star.chart2.data.DataSequence', xSeq.SupportedServiceNames) self.assertEqual(xSeq.SourceRangeRepresentation, 'Table1.%s' % expectedCellrange[col]) self.assertEqual(xSeq.Data, expectedValues[col]) self.assertEqual(xSeq.NumericalData, expectedValues[col]) self.assertEqual( [int(txtval) for txtval in xSeq.TextualData], [val for val in expectedValues[col]])
def save_as_PDF_75dpi(*args): """save current document as PDF file images will be reduced to 75dpi (JPG compression) """ # https://wiki.openoffice.org/wiki/API/Tutorials/PDF_export filter_data = { # General properties "UseLosslessCompression": True, "Quality": 100, "ReduceImageResolution": True, "MaxImageResolution": 75, # 75, 150, 300, 600, 1200 "ExportBookmarks": True, "EmbedStandardFonts": True, # Links "ExportBookmarksToPDFDestination": True, "ConvertOOoTargetToPDFTarget": True, "ExportLinksRelativeFsys": True, "PDFViewSelection": 2, # Security # ... } additional_properties = [] p = PropertyValue() p.Name = "FilterData" p.Value = uno.Any("[]com.sun.star.beans.PropertyValue", tuple(convert_dict_to_PropertyValue_List(filter_data))) additional_properties.append(p) save_as("pdf", url_addition="__75dpi", additional_properties=additional_properties)
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 createProperty(self, name, value, handle=None): pv = PropertyValue() pv.Name = name pv.Value = value if handle is not None: pv.Handle = handle return pv
def getConfig(self, key): name = 'com.sun.star.configuration.ConfigurationProvider' cp = self._create_instance(name) node = PropertyValue() node.Name = 'nodepath' node.Value = NODE try: ca = cp.createInstanceWithArguments( 'com.sun.star.configuration.ConfigurationAccess', (node,)) if ca and (ca.hasByName(NODE_CONFIG)): data = ca.getPropertyValue(NODE_CONFIG) if not data: return data data = json.loads(data) if key: value = data.get(key, '') if isinstance(value, list): return tuple(value) else: return value else: return data return except Exception as e: log.debug(e) return ''
def write(self): config_provider = self.ctx.getServiceManager().createInstanceWithContext( 'com.sun.star.configuration.ConfigurationProvider', self.ctx) node = PropertyValue() node.Name = 'nodepath' node.Value = ConfigNames.config_node cn = ConfigNames try: config_writer = config_provider.createInstanceWithArguments( 'com.sun.star.configuration.ConfigurationUpdateAccess', (node,) ) cfg_names = (cn.browser, cn.font_name, cn.char_size, cn.sdk_path) cfg_values =(self.browser, self.font_name, self.char_size, self.sdk_path) config_writer.setPropertyValues(cfg_names, cfg_values) config_writer.setHierarchicalPropertyValue(cn.pos_size, self.pos_size) if self.save_options: cfg_names = (cn.abbrev, cn.code_type, cn.show_code, cn.show_labels, cn.sorted, cn.use_pseud_props) cfg_values = (self.abbrev, self.code_type, self.show_code, self.show_labels, self.sorted, self.use_pseud_props) config_writer.setPropertyValues(cfg_names, cfg_values) self.save_options = False # store grid mode prev_grid = config_writer.getPropertyValue(cn.grid) config_writer.setPropertyValue(cn.grid, self.grid) if not (prev_grid == self.grid): self.__dict__["grid"] = prev_grid prev_tab = config_writer.getPropertyValue(cn.use_tab) config_writer.setPropertyValue(cn.use_tab, self.use_tab) if not (prev_tab == self.use_tab): self.__dict__["use_tab"] = prev_tab config_writer.commitChanges() except: raise
def newDoc(docType='swriter', hidden = True): # Make sure the docType argument is openable by OpenOffice enumList = ['swriter','simpress','scalc','sdraw','smath'] if not docType in enumList: from difflib import get_close_matches docType = get_close_matches(docType,enumList,1)[0] if len(docType)==0: print '[FATAL ERROR]: Could not find the desired type of document' exit() # Start talking to OpenOffice local = uno.getComponentContext() resolver = local.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local) context = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" ) remoteContext = context.getPropertyValue( "DefaultContext" ) desktop = context.createInstanceWithContext( "com.sun.star.frame.Desktop",remoteContext) # Initialize the properties attribute properties = () if hidden: #Generate a 'hidden' property p=PropertyValue() p.Name = 'Hidden' p.Value = True properties = (p,) # Open the new document document = desktop.loadComponentFromURL( "private:factory/"+docType,"_blank", 0, properties ) return document
def getPdfProps(): props = [] prop = PropertyValue() prop.Name = "FilterName" prop.Value = "writer_pdf_Export" props.append(prop) return tuple(props)
def _toProperties(self, dict): props = [] for key in dict: prop = PropertyValue() prop.Name = key prop.Value = dict[key] props.append(prop) return tuple(props)
def _to_properties(self, **args): props = [] for key in args: prop = PropertyValue() prop.Name = key prop.Value = args[key] props.append(prop) return tuple(props)
def convert_dict_to_PropertyValue_List(sourceDict): properties_List = [] for (key, value) in sourceDict.items(): p = PropertyValue() p.Name = key p.Value = value properties_List.append(p) return properties_List
def createTextFilter(self): # Needed for FilterName - to export to TXT import uno from com.sun.star.beans import PropertyValue TXT = PropertyValue() TXT.Name = "FilterName" TXT.Value = "Text" return TXT
def toTuple(self, args: Dict[str, Any]) -> Tuple[Any, ...]: ret = [] for k, v in args.items(): value = PropertyValue() value.Name = k value.Value = v ret.append(value) return tuple(ret)
def toTuple(self, args): ret = [] for k, v in args.items(): value = PropertyValue() value.Name = k value.Value = v ret.append(value) return tuple(ret)
def _unoProps(**args): props = [] for key in args: prop = PropertyValue() prop.Name = key prop.Value = args[key] props.append(prop) return tuple(props)
def propertyTuple(self, propDict): properties = [] for k,v in propDict.items(): property = PropertyValue() property.Name = k property.Value = v properties.append(property) return tuple(properties)
def convertClipboard(self): logging.debug("call to convertClipboard") # Get the contents from the clipboard, try to extract the data using # OpenOffice.org XML flavor clipboard = self._context.ServiceManager.createInstanceWithContext( "com.sun.star.datatransfer.clipboard.SystemClipboard", self._context) contents = clipboard.getContents() flavors = contents.getTransferDataFlavors() logging.debug("Clipboard flavors:\n%s", "* " + "\n* ".join([flavor.MimeType for flavor in flavors])) # TODO: Adding support for more flavors like richtext or plaintext mimetype = 'application/x-openoffice-embed-source-xml' \ ';windows_formatname="Star Embed Source (XML)"' found_flavor = None for flavor in flavors: if flavor.MimeType == mimetype: found_flavor = flavor break # FIXME: No suitable flavor found, warn user that nothing has been # converted # if found_flavor == None: data = contents.getTransferData(found_flavor) # Okay, since OO.o APIs only accept an URL, we have to make a temp file # in order to use it. tempFile,path = mkstemp() os.write(tempFile, data.value) tempURL = unohelper.systemPathToFileUrl(path) # Open it hiddenly hidden = PropertyValue() hidden.Name = "Hidden" hidden.Value = True document = self._desktop.loadComponentFromURL( tempURL, "_blank", 0, (hidden,)) # Let process it # TODO: Improve encoding detection so we can convert even if the # supplied font information is incorrect. self.parser.processDocument(document) # Ok, now to put it back in the clipboard dispatcher = self._context.ServiceManager.createInstanceWithContext( "com.sun.star.frame.DispatchHelper", self._context) frame = document.getCurrentController().getFrame() dispatcher.executeDispatch(frame, ".uno:SelectAll", "", 0, ()) dispatcher.executeDispatch(frame, ".uno:Copy", "", 0, ()) # Some clean ups document.close(True) os.close(tempFile) os.unlink(path)
def oo_calc(uri='private:factory/scalc'): #if no uri is passed, open a blank calc document localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver',localContext) ctx = resolver.resolve('uno:socket,host=localhost,port=5038;urp;StarOffice.ComponentContext') p = PropertyValue() p.Name = 'Hidden' p.Value = True properties = (p,) desktop = ctx.ServiceManager.createInstance('com.sun.star.frame.Desktop') return desktop.loadComponentFromURL(uri,'_blank',0,properties)
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)
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
def makeProperties(dict_): if isinstance(dict_,tuple): return dict_ if isinstance(dict_,list): return tuple(dict_) properties = [] for k,v in dict_.items(): #p = uno.createUnoStruct('com.sun.star.beans.PropertyValue') p = PropertyValue() p.Name = k p.Value = v properties.append(p) return tuple(properties)
def getRegistryProperties(group): logging.debug("PropertyManager.getRegistryProperties: " + group) compContext = uno.getComponentContext() servManager = compContext.ServiceManager provider = servManager.createInstanceWithContext("com.sun.star.configuration.ConfigurationProvider", compContext) pathArgument = PropertyValue() pathArgument.Name = "nodepath" pathArgument.Value = group aArguments = (pathArgument,) rootView = provider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationUpdateAccess", aArguments) return rootView;
def props(self, properties): '''Create a UNO-compliant tuple of properties, from tuple p_properties containing sub-tuples (s_propertyName, value).''' from com.sun.star.beans import PropertyValue res = [] for name, value in properties: prop = PropertyValue() prop.Name = name prop.Value = value res.append(prop) return tuple(res)
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)
def oo_properties(**args): """ Convert args to OpenOffice property values. """ props = [] for key in args: prop = PropertyValue() prop.Name = key prop.Value = args[key] props.append(prop) return tuple(props)
def create_property(self, name, value): """ Create an OOo style property object which are passed into some Uno methods. """ log.debug('create property OpenOffice') if is_win(): property_object = self.controller.manager.Bridge_GetStruct('com.sun.star.beans.PropertyValue') else: property_object = PropertyValue() property_object.Name = name property_object.Value = value return property_object
def propTupleFromDict(propDct): """ Returns tuple of PropertyValue elements for setting as Attributes """ from com.sun.star.beans import PropertyValue propList = [] for k in propDct: pv = PropertyValue() pv.Name = k pv.Value = propDct[k] propList.append(pv) return tuple(propList)
def ole2img(source, target, oooserver_host='localhost', oooserver_port='2002', format='png'): #fileter parameters extension, theFilter = FILTER_PARAMS[format] #Connect to OOo # get the uno component context from the PyUNO runtime localContext = uno.getComponentContext() # create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext( 'com.sun.star.bridge.UnoUrlResolver', localContext ) # connect to the running office try: print "Connecting to server %s:%s ..." % (oooserver_host, oooserver_port) ctx = resolver.resolve( 'uno:socket,host=%s,port=%s;urp;StarOffice.ComponentContext' % (oooserver_host, oooserver_port)) except NoConnectException: print "Unable to connect to OpenOffice.org instance" sys.exit(1) smgr = ctx.ServiceManager # get the central desktop object desktop = smgr.createInstanceWithContext('com.sun.star.frame.Desktop', ctx) # Now connected to OOo # load source file args = (PropertyValue('Hidden', 0, True, 0),) url = unohelper.systemPathToFileUrl(source) sourceDoc = desktop.loadComponentFromURL(url, '_blank', 0, args) # Hack/Bug : Needed to sanitize the object hierarchy for use with CurrentController url = unohelper.systemPathToFileUrl(target + 'temp.sxw') sourceDoc.storeToURL(url,()) os.remove(target + 'temp.sxw') oGraphic=smgr.createInstanceWithContext( 'com.sun.star.drawing.GraphicExportFilter', ctx) #dispatcher for copy-paste dispatcher = smgr.createInstanceWithContext( 'com.sun.star.frame.DispatchHelper', ctx) #creates an hidden draw docuement args = (PropertyValue('Hidden', 0, True, 0),) url = 'private:factory/sdraw' drawDoc = desktop.loadComponentFromURL(url, '_blank', 0, args) theOleObjects = sourceDoc.EmbeddedObjects for i in range(theOleObjects.Count): oleObject = theOleObjects.getByIndex(i) print oleObject.Name # Selection sourceDoc.CurrentController.select(oleObject) # XXX : OOo # strange random bug on importing documents from previous OOo version # sometimes the current object may not be selected # the selection remains on the previous in the loop # May be not needed any more as done previously ? # Verify the selection is ok obj = sourceDoc.CurrentController.getSelection() if obj.Name != oleObject.Name: # Save the file and select again the object # Updates the object and the can be selected url = unohelper.systemPathToFileUrl(target + 'temp.sxw') sourceDoc.storeToURL(url,()) os.remove(target + 'temp.sxw') sourceDoc.CurrentController.select(theOleObjects.getByIndex(i)) obj = sourceDoc.CurrentController.Selection # if the previous did not work # creates an image telling a problem occured if obj.Name != oleObject.Name: print "unable to process " + oleObject.Name drawingShape = drawDoc.createInstance("com.sun.star.drawing.TextShape") theSapeSize = drawingShape.Size drawDoc.DrawPages.getByIndex(0).add(drawingShape) theSapeSize.Width = 5000 theSapeSize.Height = 2500 drawingShape.setSize(theSapeSize) drawingShape.String = oleObject.Name + " - Unable to process OLE object" drawingShape.CharColor = 255 drawingShape.CharHeight = 8 objDraw = drawingShape else: # Normal behaviour # Copy dispatcher.executeDispatch(sourceDoc.CurrentController.Frame, '.uno:Copy', '', 0, ()) # Paste into draw dispatcher.executeDispatch(drawDoc.CurrentController.Frame, '.uno:Paste', '', 0, ()) # get draw object objDraw = drawDoc.CurrentController.Selection # Export oGraphic.setSourceDocument(objDraw) url = unohelper.systemPathToFileUrl(target + oleObject.Name + extension) argsExport = (PropertyValue('URL' , 0 , url, 0 ), PropertyValue('MediaType' , 0 , theFilter, 0 )) oGraphic.filter(argsExport) # Close files drawDoc.close(True) sourceDoc.close(True)
if o == "--XHTML11": filterName = "XHTML 1.1 plus MathML 2.0 File" extension = "xhtml" 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), ) inProps = PropertyValue("Hidden", 0, True, 0), for path in args: try: fileUrl = uno.absolutize(cwd, systemPathToFileUrl(path + ".sxw")) doc = desktop.loadComponentFromURL(fileUrl, "_blank", 0, inProps) if not doc: raise UnoException("Couldn't open " + fileUrl, None) saveUrl = uno.absolutize(cwd, systemPathToFileUrl(path)) doc.storeToURL(saveUrl + "." + extension, outProps) except IOException, e: sys.stderr.write("Error during conversion: " + e.Message + "\n") retVal = 1
input_cabecera_Stream = io.StringIO(input_cabecera) input_cuerpo_Stream = io.StringIO(input_cuerpo) input_pie_Stream = io.StringIO(input_pie) # Nos conectamos a libreoffice localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", localContext) ctx = resolver.resolve( "uno:socket,host=127.0.0.1,port=2002;urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) # plantilla-original.ott, es un documento de libreoffice que se encuentra en blanco, para el proposito especifico posee solo encabezado (no requeria el uso de pie). plantilla = currDir + "/template.ott" oTemplateProperties = (PropertyValue("AsTemplate", 0, True, 0), ) document = desktop.loadComponentFromURL("file://" + plantilla, "_blank", 0, oTemplateProperties) #document = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, ()) class InputStream(unohelper.Base, XInputStream, XSeekable): """ Minimal Implementation of XInputStream """ def __init__(self, inStream): self.stream = inStream self.stream.seek(0, os.SEEK_END) self.size = self.stream.tell() def readBytes(self, retSeq, nByteCount): retSeq = self.stream.read(nByteCount)
def createDoc(): """creates a new writer document and inserts a table with some data (also known as the SWriter sample)""" ctx = uno.getComponentContext() smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx) # open a writer document doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () ) text = doc.Text cursor = text.createTextCursor() text.insertString( cursor, "The first line in the newly created text document.\n", 0 ) text.insertString( cursor, "Now we are in the second line\n" , 0 ) # Create a text table noRows = 5 noCols = 4 table = daisyCreateTable(doc, cursor, noCols, noRows) rows = table.Rows table.setPropertyValue( "BackTransparent", uno.Bool(0) ) table.setPropertyValue( "BackColor", 13421823 ) row = rows.getByIndex(0) row.setPropertyValue( "BackTransparent", uno.Bool(0) ) row.setPropertyValue( "BackColor", 6710932 ) textColor = 16777215 insertTextIntoCell( table, "A1", "FirstColumn", textColor ) insertTextIntoCell( table, "B1", "SecondColumn", textColor ) insertTextIntoCell( table, "C1", "ThirdColumn", textColor ) insertTextIntoCell( table, "D1", "SUM", textColor ) values = ( (22.5,21.5,121.5), (5615.3,615.3,-615.3), (-2315.7,315.7,415.7) ) table.getCellByName("A2").setValue(22.5) table.getCellByName("B2").setValue(5615.3) table.getCellByName("C2").setValue(-2315.7) table.getCellByName("D2").setFormula("sum <A2:C2>") table.getCellByName("A3").setValue(21.5) table.getCellByName("B3").setValue(615.3) table.getCellByName("C3").setValue(-315.7) table.getCellByName("D3").setFormula("sum <A3:C3>") table.getCellByName("A4").setValue(121.5) table.getCellByName("B4").setValue(-615.3) table.getCellByName("C4").setValue(415.7) table.getCellByName("D4").setFormula("sum <A4:C4>") cursor.setPropertyValue( "CharColor", 255 ) cursor.setPropertyValue( "CharShadowed", uno.Bool(1) ) BR(doc, cursor) text.insertString( cursor, " This is a colored Text - blue with shadow\n" , 0 ) BR(doc, cursor) textFrame = doc.createInstance( "com.sun.star.text.TextFrame" ) textFrame.setSize( Size(15000,400)) textFrame.setPropertyValue( "AnchorType" , AS_CHARACTER ) text.insertTextContent( cursor, textFrame, 0 ) textInTextFrame = textFrame.getText() cursorInTextFrame = textInTextFrame.createTextCursor() textInTextFrame.insertString( cursorInTextFrame, "The first line in the newly created text frame.", 0 ) textInTextFrame.insertString( cursorInTextFrame, "\nWith this second line the height of the rame raises.",0) BR(doc, cursor) cursor.setPropertyValue( "CharColor", 65536 ) cursor.setPropertyValue( "CharShadowed", uno.Bool(0) ) daisyImportTextFile(doc, cursor, "/home/jacobw/textfile.txt") daisyPrintSineTable(doc, cursor) #daisyPrintDirList(doc, cursor) text.insertString( cursor, " That's all for now !!", 0 ) BR(doc, cursor) #daisyReadCsvFile(doc, cursor, "/home/jacobw/textfile.txt") text.insertString( cursor, "No, it wasnt!!", 0 ) BR(doc, cursor) # Save to file properties = ( PropertyValue('Overwrite', 0, True, 0), ) doc.storeToURL('file:///home/jacobw/test.odt', properties) #oTables = doc.TextTables #text.insertString( cursor, oTables.Length, 0 ) table.Rows.insertByIndex(table.Rows.getCount(),1) table.Rows.insertByIndex(table.Rows.getCount(),1) table.Rows.insertByIndex(table.Rows.getCount(),1) text.insertString( cursor, str(table.Rows.getCount()), 0) table2 = daisyCreateTable(doc, cursor, noCols, noRows) # for tableName in doc.TextTables: text.insertString( cursor, "There are "+ str(doc.TextTables.getCount()) + " tables in the document", 0) BR(doc, cursor) dWrite(doc, cursor, "The names of these are:") for tableId in doc.TextTables.getElementNames(): BR(doc, cursor) text.insertString( cursor, tableId, 0) BR(doc, cursor)
def dict_to_property(values, uno_any=False): ps = tuple([PropertyValue(Name=n, Value=v) for n, v in values.items()]) if uno_any: ps = uno.Any('[]com.sun.star.beans.PropertyValue', ps) return ps
def mkPropertyValues(**kwargs): '''mkPropertyValues(Name=Value, Name=Value,...) -> (PropertyValue, PropertyValue,...) ex. : mkPropertyValues(Hidden=True, ReadOnly=False)''' from com.sun.star.beans import PropertyValue return tuple(PropertyValue(k, 0, kwargs[k], 0) for k in kwargs)
def save_as(\ dest_type=None,\ currentDoc=None,\ doc_type=None,\ url_current=None,\ url_addition=None,\ additional_properties=None\ ): if dest_type: if not currentDoc: currentDoc = XSCRIPTCONTEXT.getDocument() if not doc_type: doc_type = getDocType(currentDoc) if not url_current: url_current = currentDoc.getLocation() # currentDoc = XSCRIPTCONTEXT.getDocument() # doc_type = getDocType(currentDoc) # url_current = currentDoc.getLocation() if url_current: url_new = compose_new_URL( doc_type, # doc_type dest_type, # dest_type, url_current, # url_current, url_addition # url_addition ) properties = [] p = PropertyValue() p.Name = 'FilterName' p.Value = doc_type[dest_type]['filter'] properties.append(p) p = PropertyValue() p.Name = 'Overwrite' p.Value = True properties.append(p) p = PropertyValue() p.Name = 'InteractionHandler' p.Value = '' properties.append(p) if additional_properties: properties.extend(additional_properties) currentDoc.storeToURL(url_new, tuple(properties)) else: print("pleas first save your file!") # raise NoLocationError() # showDialog( # 'No Location', # 'No Location found.\n please first save your file' # ) # dialog_example() box = MessageBox() box.msgbox( title='No Location', message='No Location found.\nplease save your file first') else: print("no type given. i cant work...")
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( "Could not open stream for unknown reason", None) doc.storeToURL("private:stream", outProps) except IOException as e: sys.stderr.write("Error during conversion: " + e.Message + "\n") retVal = 1 except UnoException as e: sys.stderr.write("Error (" + repr(e.__class__) + ") during conversion: " + e.Message + "\n") retVal = 1 if doc: doc.dispose() except UnoException as e: sys.stderr.write("Error (" + repr(e.__class__) + "): " + e.Message + "\n") retVal = 1 except getopt.GetoptError as e: sys.stderr.write(str(e) + "\n") usage() retVal = 1 sys.exit(retVal)
class Options: def __init__(self, args): self.connection = None self.doctype = None self.exportfilter = [] self.filenames = [] self.format = None self.importfilter = "" self.listener = False self.kill = False self.output = None self.pipe = None self.port = '2002' self.server = 'localhost' self.showlist = False self.stdout = False self.template = None self.timeout = 6 self.verbose = 0 self.remove = None ### Get options from the commandline try: opts, args = getopt.getopt (args, 'c:d:e:f:hi:Llko:p:s:t:T:vr:', ['connection=', 'doctype=', 'export', 'format=', 'help', 'import', 'listener', 'kill', 'output=', 'outputpath', 'pipe=', 'port=', 'server=', 'timeout=', 'show', 'stdout', 'template', 'verbose', 'version', '--remove='] ) except getopt.error, exc: print 'unoconv: %s, try unoconv -h for a list of all the options' % str(exc) sys.exit(255) for opt, arg in opts: if opt in ['-h', '--help']: self.usage() print self.help() sys.exit(1) elif opt in ['-c', '--connection']: self.connection = arg elif opt in ['-d', '--doctype']: self.doctype = arg elif opt in ['-e', '--export']: l = arg.split('=') if len(l) == 2: (name, value) = l if value in ('True', 'true'): self.exportfilter.append( PropertyValue( name, 0, True, 0 ) ) elif value in ('False', 'false'): self.exportfilter.append( PropertyValue( name, 0, False, 0 ) ) else: self.exportfilter.append( PropertyValue( name, 0, value, 0 ) ) else: print >>sys.stderr, 'Warning: Option %s cannot be parsed, ignoring.' % arg elif opt in ['-f', '--format']: self.format = arg elif opt in ['-i', '--import']: self.importfilter = arg elif opt in ['-l', '--listener']: self.listener = True elif opt in ['-k', '--kill']: self.kill = True elif opt in ['-o', '--output']: self.output = arg elif opt in ['--outputpath']: print >>sys.stderr, 'Warning: This option is deprecated by --output.' % arg self.output = arg elif opt in ['--pipe']: self.pipe = arg elif opt in ['-p', '--port']: self.port = arg elif opt in ['-s', '--server']: self.server = arg elif opt in ['--show']: self.showlist = True elif opt in ['--stdout']: self.stdout = True elif opt in ['-t', '--template']: self.template = arg elif opt in ['-T', '--timeout']: self.timeout = int(arg) elif opt in ['-v', '--verbose']: self.verbose = self.verbose + 1 elif opt in ['-r', '--remove']: self.remove = arg elif opt in ['--version']: self.version() sys.exit(255) ### Enable verbosity if self.verbose >= 3: print >>sys.stderr, 'Verbosity set to level %d' % (self.verbose - 1) self.filenames = args if self.remove: os.remove(self.remove) print >> sys.stderr, "%s file created by OpenOffice was successfully removed." % self.remove sys.stderr.flush() sys.exit(0) if self.kill: try: pid = int(open(CFG_SOFFICE_PID, 'r').read()) os.kill(pid, signal.SIGTERM) time.sleep(2) try: os.kill(pid, signal.SIGKILL) except: pass except Exception, err: print >> sys.stderr, 'Couldn\'t kill soffice.bin: %s' % err sys.exit(1) print >>sys.stderr, 'soffice.bin was hopefully killed.' sys.exit(0)
def dict_to_propseq(d): from com.sun.star.beans import PropertyValue DIRECT_VALUE = uno.Enum('com.sun.star.beans.PropertyState', 'DIRECT_VALUE') return tuple( PropertyValue(k, 0, unofy_value(d[k]), DIRECT_VALUE) for k in d)
def queryImageAndPaste(self, host, port, url, width, height, paraadjust): """ Query an image trough a socket, then pastes it into the Text document :param host: an IP address, "localhost" by default :param port: a port for the socket, 45594 by default :param url: a well-formed url, to GET a response containing an image in SVG format (maybe later, also PNG?) :param width: might be used later :param height: might be used later :param paraadjust: might be used later """ desktop = self.ctx.ServiceManager.createInstanceWithContext( 'com.sun.star.frame.Desktop', self.ctx) doc = desktop.getCurrentComponent() cursor = doc.getCurrentController().getViewCursor() if hasattr(doc, "Text"): undoManager = doc.getUndoManager() undoManager.enterUndoContext("Insert screenshot from Eyes17") # do the work here ctx = uno.getComponentContext() graphicprovider = ctx.ServiceManager.createInstance( "com.sun.star.graphic.GraphicProvider") istream = ctx.ServiceManager.createInstanceWithContext( "com.sun.star.io.SequenceInputStream", ctx) conn = http.client.HTTPConnection(host, port) try: conn.request("GET", url) except: doc.Text.insertString( cursor, f"EYES17 screenshot failed: could not connect to {host}:{port}", 0) doc.Text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0) return r1 = conn.getresponse() if r1.reason != "OK": doc.Text.insertString( cursor, f"EYES17 screenshot failed: Could not get http://{host}:{port}. Error: {r1.status} {r1.reason}", 0) doc.Text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0) return fbytes = r1.read() istream.initialize((uno.ByteSequence(fbytes), )) graphic = graphicprovider.queryGraphic( (PropertyValue('InputStream', 0, istream, 0), )) if graphic.SizePixel is None: # Then we're likely dealing with vector graphics. Then we try to # get the "real" size, which is enough information to # determine the aspect ratio original_size = graphic.Size100thMM else: original_size = graphic.SizePixel graphic_object_shape = doc.createInstance( 'com.sun.star.drawing.GraphicObjectShape') graphic_object_shape.Graphic = graphic size = self.adjustSize(original_size, width=width, height=height) graphic_object_shape.setSize(size) thisgraphicobject = doc.createInstance( "com.sun.star.text.TextGraphicObject") thisgraphicobject.Graphic = graphic_object_shape.Graphic thisgraphicobject.setSize(size) ## for future enhancements: take in account paraadjust ## if paraadjust: ## oldparaadjust = cursor.ParaAdjust ## cursor.ParaAdjust = paraadjust ## ######################################################### doc.Text.insertTextContent(cursor, thisgraphicobject, False) doc.Text.insertControlCharacter(cursor, PARAGRAPH_BREAK, 0) ## for future enhancements: take in account paraadjust ## if paraadjust: ## cursor.ParaAdjust = oldparaadjust ## ######################################################### undoManager.leaveUndoContext() return
url_original = uno.systemPathToFileUrl(sys.argv[1]) url_save = uno.systemPathToFileUrl(sys.argv[2]) try: ### Get Service Manager context = uno.getComponentContext() resolver = context.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", context) ctx = resolver.resolve( "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager ### Load document properties = [] p = PropertyValue() p.Name = "Hidden" p.Value = True properties.append(p) properties = tuple(properties) desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) except NoConnectException, e: sys.stderr.write("OpenOffice process not found or not listening (" + e.Message + ")\n") sys.exit(1) except IllegalArgumentException, e: sys.stderr.write("The url is invalid ( " + e.Message + ")\n") sys.exit(1) except RuntimeException, e:
def main(): retVal = 0 doc = None try: opts, args = getopt.getopt(sys.argv[1:], "hc:o:f:s:r:x:", ["help", "connection-string="]) url = "uno:socket,host=localhost,port=2004;urp;StarOffice.ComponentContext" outputPath = "/tmp/" search = "" replace = "*" regex = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-c", "--connection-string"): url = "uno:" + a + ";urp;StarOffice.ComponentContext" elif o == "-o": outputPath = a elif o == "-s": search = a elif o == "-r": replace = a elif o == "-x": regex = a == "true" if not len(args): usage() sys.exit() ctxLocal = uno.getComponentContext() smgrLocal = ctxLocal.ServiceManager resolver = smgrLocal.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", ctxLocal) ctx = resolver.resolve(url) smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) cwd = systemPathToFileUrl(getcwd()) inProps = PropertyValue("Hidden", 0, True, 0), for path in args: try: outputFile = outputPath fileUrl = uno.absolutize(cwd, systemPathToFileUrl(path)) outputUrl = uno.absolutize(cwd, systemPathToFileUrl(outputFile)) doc = desktop.loadComponentFromURL(fileUrl, "_blank", 0, inProps) if not doc: raise UnoException( "Could not open stream for unknown reason", None) srd = doc.createReplaceDescriptor() srd.setPropertyValue("SearchRegularExpression", regex) srd.setSearchString(search) srd.setReplaceString(replace) doc.replaceAll(srd) doc.storeToURL(outputUrl, ()) except IOException as e: sys.stderr.write("Error during conversion: " + e.Message + "\n") retVal = 1 except UnoException as e: sys.stderr.write("Error (" + repr(e.__class__) + ") during conversion: " + e.Message + "\n") retVal = 1 if doc: doc.dispose() except UnoException as e: sys.stderr.write("Error (" + repr(e.__class__) + "): " + e.Message + "\n") retVal = 1 except getopt.GetoptError as e: sys.stderr.write(str(e) + "\n") usage() retVal = 1 sys.exit(retVal)
def convert(self, inputfn, target_format, conversion_options=None): document = None self.log.debug('Input file: %s', inputfn) if not os.path.exists(inputfn): self.log.error('unoconv: file `%s\' does not exist.' % inputfn) return None try: ### Import phase phase = "import" ### Load inputfile input_md = UnoProps(Hidden=True, ReadOnly=True, UpdateDocMode=QUIET_UPDATE) inputurl = unohelper.absolutize( self.cwd, unohelper.systemPathToFileUrl(inputfn)) document = self.desktop.loadComponentFromURL( inputurl, "_blank", 0, input_md) if not document: raise UnoException( "The document '%s' could not be opened." % inputurl, None) ### Export phase phase = "export" (outputfn, ext) = os.path.splitext(inputfn) export_filter, out_exten = get_filter(ext, target_format) outputprops = UnoProps(FilterName=export_filter, OutputStream=OutputStream(), Overwrite=True) ### Set default filter options if conversion_options: filter_data = UnoProps(**conversion_options) outputprops += (PropertyValue( "FilterData", 0, uno.Any( "[]com.sun.star.beans.PropertyValue", tuple(filter_data), ), 0), ) outputfn = outputfn + os.extsep + out_exten outputurl = unohelper.absolutize( self.cwd, unohelper.systemPathToFileUrl(outputfn)) self.log.debug("Output file: %s" % outputfn) try: document.storeToURL(outputurl, tuple(outputprops)) except IOException as e: raise UnoException( "Unable to store document to %s (ErrCode %d)\n\nProperties: %s" % (outputurl, e.ErrCode, outputprops), None) phase = "dispose" document.dispose() document.close(True) exitcode = 0 return outputfn except SystemError as e: self.log.fatal("unoconv: SystemError during %s phase:\n%s" % (phase, e)) exitcode = 1 except RuntimeException as e: self.log.fatal( "unoconv: RuntimeException during %s phase:\nOffice probably died. %s" % (phase, e)) exitcode = 6 except DisposedException as e: self.log.fatal( "unoconv: DisposedException during %s phase:\nOffice probably died. %s" % (phase, e)) exitcode = 7 except IllegalArgumentException as e: self.log.fatal( "UNO IllegalArgument during %s phase:\nSource file cannot be read. %s" % (phase, e)) exitcode = 8 except IOException as e: # for attr in dir(e): print '%s: %s', (attr, getattr(e, attr)) self.log.fatal("unoconv: IOException during %s phase:\n%s" % (phase, e.Message)) exitcode = 3 except CannotConvertException as e: # for attr in dir(e): print '%s: %s', (attr, getattr(e, attr)) self.log.fatal( "unoconv: CannotConvertException during %s phase:\n%s" % (phase, e.Message)) exitcode = 4 except UnoException as e: if hasattr(e, 'ErrCode'): self.log.fatal( "unoconv: UnoException during %s phase in %s (ErrCode %d)" % (phase, repr(e.__class__), e.ErrCode)) exitcode = e.ErrCode pass if hasattr(e, 'Message'): self.log.fatal("unoconv: UnoException during %s phase:\n%s" % (phase, e.Message)) exitcode = 5 else: self.log.fatal("unoconv: UnoException during %s phase in %s" % (phase, repr(e.__class__))) exitcode = 2 pass return exitcode
def convert(self, inputfn): global exitcode document = None outputfmt = self.getformat(inputfn) if op.verbose > 0: print >>sys.stderr, 'Input file:', inputfn if not os.path.exists(inputfn): print >>sys.stderr, 'unoconv: file `%s\' does not exist.' % inputfn exitcode = 1 try: ### Load inputfile inputprops = ( PropertyValue( "Hidden", 0, True, 0 ), PropertyValue( "ReadOnly", 0, True, 0 ), PropertyValue( "FilterOptions", 0, op.importfilter, 0 ), ) inputurl = unohelper.absolutize(self.cwd, unohelper.systemPathToFileUrl(inputfn)) document = self.desktop.loadComponentFromURL( inputurl , "_blank", 0, inputprops ) if not document: raise UnoException("File could not be loaded by OpenOffice", None) ### Import style template if op.template: if os.path.exists(op.template): if op.verbose > 0: print >>sys.stderr, 'Template file:', op.template templateprops = ( PropertyValue( "OverwriteStyles", 0, True, 0), ) templateurl = unohelper.absolutize(self.cwd, unohelper.systemPathToFileUrl(op.template)) document.StyleFamilies.loadStylesFromURL(templateurl, templateprops) else: print >>sys.stderr, 'unoconv: template file `%s\' does not exist.' % op.template exitcode = 1 info(1, "Selected output format: %s" % outputfmt) info(1, "Selected ooffice filter: %s" % outputfmt.filter) info(1, "Used doctype: %s" % outputfmt.doctype) ### Update document links try: document.updateLinks() except AttributeError: # the document doesn't implement the XLinkUpdate interface pass ### Update document indexes try: document.refresh() indexes = document.getDocumentIndexes() except AttributeError: # the document doesn't implement the XRefreshable and/or # XDocumentIndexesSupplier interfaces pass else: for i in range(0, indexes.getCount()): indexes.getByIndex(i).update() ### Write outputfile outputprops = [ # PropertyValue( "FilterData" , 0, ( PropertyValue( "SelectPdfVersion" , 0, 1 , uno.getConstantByName( "com.sun.star.beans.PropertyState.DIRECT_VALUE" ) ) ), uno.getConstantByName( "com.sun.star.beans.PropertyState.DIRECT_VALUE" ) ), PropertyValue( "FilterData", 0, uno.Any("[]com.sun.star.beans.PropertyValue", tuple( op.exportfilter ), ), 0 ), PropertyValue( "FilterName", 0, outputfmt.filter, 0), # PropertyValue( "SelectionOnly", 0, True, 0 ), PropertyValue( "OutputStream", 0, OutputStream(), 0 ), PropertyValue( "Overwrite", 0, True, 0 ), ] if outputfmt.filter == 'Text (encoded)': outputprops.append(PropertyValue( "FilterFlags", 0, "UTF8, LF", 0)) ### BEG Invenio customizations elif outputfmt.filter == 'writer_pdf_Export': ## To enable PDF/A outputprops.append(PropertyValue( "SelectPdfVersion", 0, 1, 0)) ### END Invenio customizations if not op.stdout: (outputfn, ext) = os.path.splitext(inputfn) if not op.output: outputfn = outputfn + os.extsep + outputfmt.extension elif os.path.isdir(op.output): outputfn = os.path.join(op.output, os.path.basename(outputfn) + os.extsep + outputfmt.extension) elif len(op.filenames) > 1: outputfn = op.output + os.extsep + outputfmt.extension else: outputfn = op.output outputurl = unohelper.absolutize( self.cwd, unohelper.systemPathToFileUrl(outputfn) ) document.storeToURL(outputurl, tuple(outputprops) ) info(1, "Output file: %s" % outputfn) else: document.storeToURL("private:stream", tuple(outputprops) ) document.dispose() document.close(True) except SystemError, e: error("unoconv: SystemError during conversion: %s" % e) error("ERROR: The provided document cannot be converted to the desired format.") exitcode = 1
def getProps(self, properties=[]): props = [] for name, x, value, y in properties: prop = PropertyValue(name, x, value, y) props.append(prop) return tuple(props)
def generateTestTuple(self, values): properties = [] for i in values: properties.append((PropertyValue(Name='n' + str(i), Value='v' + str(i)), )) return tuple(properties)
def doProofreading(self, aDocumentIdentifier, aText, aLocale, nStartOfSentencePos, nSuggestedBehindEndOfSentencePosition, aProperties): logging.debug("GrammarChecker.doProofreading") result = ProofreadingResult() result.aDocumentIdentifier = aDocumentIdentifier result.xFlatParagraph = None result.aText = aText result.aLocale = aLocale result.nStartOfSentencePosition = nStartOfSentencePos result.nBehindEndOfSentencePosition = nSuggestedBehindEndOfSentencePosition result.xProofreader = self # We read from registry on each check – it probably # doesn't change most of the time, but it *can* change # if user edited the plugin options, so this is at # least safe: ignoredRules = readIgnoredRules() # TODO: get from PropertyManager instead, see reloadDivvunSettings DivvunHandlePool.mutex.acquire() try: instance = DivvunHandlePool.getInstance() if instance is None: logging.error("GrammarChecker.doProofreading could not initialize libdivvun!") return result divvun = instance.getHandle(aLocale) if divvun is None: logging.error("GrammarChecker.doProofreading couldn't get an instance for locale %s"%(aLocale,)) logging.error("DivvunHandlePool.initializationErrors = %s"%(instance.getInitializationStatus(),)) return result gcErrors = [] logging.info("Checking '%s', nStartOfSentencePos=%d, nSuggestedBehindEndOfSentencePosition=%d", aText, nStartOfSentencePos, nSuggestedBehindEndOfSentencePosition) for dError in libdivvun.proc_errs_bytes(divvun, aText): startPos = dError.beg errorLength = dError.end - dError.beg logging.info("dError on form=%s at (%d,%d) replacements: %s", dError.form, dError.beg, dError.end, dError.rep) if dError.beg < result.nStartOfSentencePosition: logging.info("beg %d < result.nStartOfSentencePosition %d, continue", dError.beg, result.nStartOfSentencePosition) continue if dError.beg >= result.nBehindEndOfSentencePosition: logging.info("beg %d >= result.nBehindEndOfSentencePosition %d, break", dError.beg, result.nBehindEndOfSentencePosition) break if dError.beg + errorLength > result.nBehindEndOfSentencePosition: logging.info("dError.beg %d + errorLength %d > result.nBehindEndOfSentencePosition %d, incf", dError.beg, errorLength, result.nBehindEndOfSentencePosition) result.nBehindEndOfSentencePosition = dError.beg + errorLength logging.info("dError on form=%s at (%d,%d) replacements: %s", dError.form, dError.beg, dError.end, dError.rep) ruleIdentifier = dError.err if ruleIdentifier in ignoredRules: logging.debug("Ignored error with rule " + ruleIdentifier) continue suggestions = dError.rep gcError = SingleProofreadingError() gcErrors.append(gcError) gcError.nErrorStart = startPos gcError.nErrorLength = errorLength gcError.nErrorType = PROOFREADING comment = dError.dsc gcError.aShortComment = comment gcError.aFullComment = comment gcError.aRuleIdentifier = ruleIdentifier if False: # We are not web yet, TODO detailUrl = PropertyValue() detailUrl.Name = "FullCommentURL" detailUrl.Value = "http://divvun.no/gchelp/" + aLocale.Language + "/" + ruleIdentifier + ".html" gcError.aProperties = (detailUrl,) # add suggestions if len(suggestions) > 0: gcError.aSuggestions = tuple(suggestions) result.aErrors = tuple(gcErrors) result.nStartOfNextSentencePosition = result.nBehindEndOfSentencePosition logging.info("return result, errors: %d", len(result.aErrors)) return result finally: DivvunHandlePool.mutex.release()
def create_graphic(ctx, url): """ Create graphic instance for image URL. """ return create_service( ctx, "com.sun.star.graphic.GraphicProvider").\ queryGraphic((PropertyValue("URL", -1, url, 0),))
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) except IllegalArgumentException, e: print >> sys.stderr, 'Impossible de convertir le fichier pour les raisons suivantes : \n' print >> sys.stderr, e sys.exit(0) outputDoc=systemPathToFileUrl(conf["main"]["tmpPath"]+"/"+inputs["OutputDoc"]["value"]) tmp=inputs["OutputDoc"]["value"].split('.'); outputFormat={"pdf": "writer_pdf_Export", "html": "HTML (StarWriter)","odt": "writer8","doc": "MS Word 97","rtf": "Rich Text Format"} for i in range(len(outputFormat)) : if tmp[1]==outputFormat.keys()[i] : filterName=outputFormat[tmp[1]] prop1Fich = ( PropertyValue( "FilterName" , 0, filterName , 0 ), PropertyValue( "Overwrite" , 0, True , 0 ) ) break myDocument.storeToURL(outputDoc,prop1Fich) myDocument.close(True) ctx.ServiceManager outputs["OutputedDocument"]={"value": inputs["OutputDoc"]["value"],"dataType": "string"} return 3
def to_blank_lines(): """Replace scene dividers with blank lines This will replace the three-line "* * *" scene dividers with single blank lines. The style of the scene-dividing lines will be changed from _Heading 4_ to _Heading 5_. """ pStyles = XSCRIPTCONTEXT.getDocument().StyleFamilies.getByName( 'ParagraphStyles') # pStyles = ThisComponent.StyleFamilies.getByName("ParagraphStyles") document = XSCRIPTCONTEXT.getDocument().CurrentController.Frame # document = ThisComponent.CurrentController.Frame ctx = XSCRIPTCONTEXT.getComponentContext() smgr = ctx.getServiceManager() dispatcher = smgr.createInstanceWithContext( "com.sun.star.frame.DispatchHelper", ctx) # dispatcher = createUnoService("com.sun.star.frame.DispatchHelper") args1 = [] for i in range(18): args1.append(PropertyValue()) # dim args1(18) as new com.sun.star.beans.PropertyValue args1[0].Name = "SearchItem.StyleFamily" args1[0].Value = 2 args1[1].Name = "SearchItem.CellType" args1[1].Value = 0 args1[2].Name = "SearchItem.RowDirection" args1[2].Value = True args1[3].Name = "SearchItem.AllTables" args1[3].Value = False args1[4].Name = "SearchItem.Backward" args1[4].Value = False args1[5].Name = "SearchItem.Pattern" args1[5].Value = True args1[6].Name = "SearchItem.Content" args1[6].Value = False args1[7].Name = "SearchItem.AsianOptions" args1[7].Value = False args1[8].Name = "SearchItem.AlgorithmType" args1[8].Value = 0 args1[9].Name = "SearchItem.SearchFlags" args1[9].Value = 65536 args1[10].Name = "SearchItem.SearchString" args1[10].Value = pStyles.getByName["Heading 4"].DisplayName args1[11].Name = "SearchItem.ReplaceString" args1[11].Value = pStyles.getByName["Heading 5"].DisplayName args1[12].Name = "SearchItem.Locale" args1[12].Value = 255 args1[13].Name = "SearchItem.ChangedChars" args1[13].Value = 2 args1[14].Name = "SearchItem.DeletedChars" args1[14].Value = 2 args1[15].Name = "SearchItem.InsertedChars" args1[15].Value = 2 args1[16].Name = "SearchItem.TransliterateFlags" args1[16].Value = 1280 args1[17].Name = "SearchItem.Command" args1[17].Value = 3 args1[18].Name = "Quiet" args1[18].Value = True dispatcher.executeDispatch(document, ".uno:ExecuteSearch", "", 0, args1) args2 = [] for i in range(18): args2.append(PropertyValue()) # dim args2(18) as new com.sun.star.beans.PropertyValue args2[0].Name = "SearchItem.StyleFamily" args2[0].Value = 2 args2[1].Name = "SearchItem.CellType" args2[1].Value = 0 args2[2].Name = "SearchItem.RowDirection" args2[2].Value = True args2[3].Name = "SearchItem.AllTables" args2[3].Value = False args2[4].Name = "SearchItem.Backward" args2[4].Value = False args2[5].Name = "SearchItem.Pattern" args2[5].Value = True args2[6].Name = "SearchItem.Content" args2[6].Value = False args2[7].Name = "SearchItem.AsianOptions" args2[7].Value = False args2[8].Name = "SearchItem.AlgorithmType" args2[8].Value = 0 args2[9].Name = "SearchItem.SearchFlags" args2[9].Value = 65536 args2[10].Name = "SearchItem.SearchString" args2[10].Value = pStyles.getByName["Heading 5"].DisplayName args2[11].Name = "SearchItem.ReplaceString" args2[11].Value = pStyles.getByName["Heading 5"].DisplayName args2[12].Name = "SearchItem.Locale" args2[12].Value = 255 args2[13].Name = "SearchItem.ChangedChars" args2[13].Value = 2 args2[14].Name = "SearchItem.DeletedChars" args2[14].Value = 2 args2[15].Name = "SearchItem.InsertedChars" args2[15].Value = 2 args2[16].Name = "SearchItem.TransliterateFlags" args2[16].Value = 1280 args2[17].Name = "SearchItem.Command" args2[17].Value = 1 args2[18].Name = "Quiet" args2[18].Value = True dispatcher.executeDispatch(document, ".uno:ExecuteSearch", "", 0, args2) args3 = [] for i in range(18): args3.append(PropertyValue()) # dim args3(18) as new com.sun.star.beans.PropertyValue args3[0].Name = "SearchItem.StyleFamily" args3[0].Value = 2 args3[1].Name = "SearchItem.CellType" args3[1].Value = 0 args3[2].Name = "SearchItem.RowDirection" args3[2].Value = True args3[3].Name = "SearchItem.AllTables" args3[3].Value = False args3[4].Name = "SearchItem.Backward" args3[4].Value = False args3[5].Name = "SearchItem.Pattern" args3[5].Value = False args3[6].Name = "SearchItem.Content" args3[6].Value = False args3[7].Name = "SearchItem.AsianOptions" args3[7].Value = False args3[8].Name = "SearchItem.AlgorithmType" args3[8].Value = 0 args3[9].Name = "SearchItem.SearchFlags" args3[9].Value = 71680 args3[10].Name = "SearchItem.SearchString" args3[10].Value = "* * *" args3[11].Name = "SearchItem.ReplaceString" args3[11].Value = "" args3[12].Name = "SearchItem.Locale" args3[12].Value = 255 args3[13].Name = "SearchItem.ChangedChars" args3[13].Value = 2 args3[14].Name = "SearchItem.DeletedChars" args3[14].Value = 2 args3[15].Name = "SearchItem.InsertedChars" args3[15].Value = 2 args3[16].Name = "SearchItem.TransliterateFlags" args3[16].Value = 1280 args3[17].Name = "SearchItem.Command" args3[17].Value = 3 args3[18].Name = "Quiet" args3[18].Value = True dispatcher.executeDispatch(document, ".uno:ExecuteSearch", "", 0, args3)
from unohelper import systemPathToFileUrl, absolutize from com.sun.star.beans import PropertyValue outputfile = "helloworld.odt" url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" 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()) destFile = absolutize(cwd, systemPathToFileUrl(outputfile)) inProps = PropertyValue("Hidden", 0, True, 0), newdoc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, inProps) #get the XText interface text = newdoc.Text #create an XTextRange at the end of the document tRange = text.End #and set the string tRange.String = "Hello World (in Python)" print("Hello World (in Python)") newdoc.storeAsURL(destFile, ()) newdoc.dispose() print(f"File {outputfile} created.") # run this file with `python3 helloworld.py` # then close libreoffice-socket: kill PID
def insertStream(cursor, aStream): inPropsce = (PropertyValue("FilterName", 0, "Rich Text Format", 0), PropertyValue("InputStream", 0, InputStream(aStream), 0)) cursor.insertDocumentFromURL("private:stream", inPropsce) #text.insertControlCharacter(cursor, uno.getConstantByName("com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK"), 0) cursor.gotoEnd(False)
def _getLOVersion(ctx, smgr): # LibreOfficeの名前とバージョンを返す。 cp = smgr.createInstanceWithContext('com.sun.star.configuration.ConfigurationProvider', ctx) node = PropertyValue(Name = 'nodepath', Value = 'org.openoffice.Setup/Product' ) # share/registry/main.xcd内のノードパス。 ca = cp.createInstanceWithArguments('com.sun.star.configuration.ConfigurationAccess', (node,)) return ca.getPropertyValues(('ooName', 'ooSetupVersion')) # LibreOfficeの名前とバージョンをタプルで返す。
def convert_html(input, format_name, images=None): out_filter = fmts.get_filter_by_name(format_name) if not out_filter: raise Exception("Unsupported format name %s" % (format_name)) infile = None outfile = None out_f = None try: desktop = get_desktop() start_processing() # create in/out files temp_dir = mkdtemp(prefix="cm_") # in indir_name = os.path.join(temp_dir, THE_INDIR) os.mkdir(indir_name) infile_name = os.path.join(indir_name, THE_INFILE + '.html') # out outdir_name = os.path.join(temp_dir, THE_OUTDIR) os.mkdir(outdir_name) outfile_name = os.path.join(outdir_name, THE_OUTFILE) # write infile infile = open(infile_name, 'w') input = to_string(input) infile.write(input) infile.close() # fix perms # TODO: group permission should suffice os.chmod(temp_dir, 0755) # read os.chmod(indir_name, 0755) # read os.chmod(infile_name, 0755) # read os.chmod(outdir_name, 0777) # read / write inProps = PropertyValue("Hidden", 0, True, 0), doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, inProps) text = doc.Text cursor = text.createTextCursor() fileUrl = systemPathToFileUrl(infile_name) cursor.insertDocumentFromURL(fileUrl, ()) properties = (PropertyValue("Hidden", 0, True, 0), PropertyValue("FilterName", 0, out_filter, 0)) doc.storeToURL('file://%s' % outfile_name, tuple(properties)) out_f = open(outfile_name, 'r') output = out_f.read() return output finally: end_processing() try: if out_f: out_f.close() if infile: infile.close() top = temp_dir for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) os.rmdir(top) except: # TODO : warn pass
def create_property_value(name, value): property_value = PropertyValue() property_value.Name = name property_value.Value = value return property_value
def convert(input, format_name, unicode=False): logging.info('convert') out_filter = fmts.get_filter_by_name(format_name) if not out_filter: raise Exception("Unsupported format name %s" % (format_name)) infile = None outfile = None out_f = None try: desktop = get_desktop() start_processing() # create in/out files temp_dir = mkdtemp(prefix="cm_") # in indir_name = os.path.join(temp_dir, THE_INDIR) os.mkdir(indir_name) infile_name = os.path.join(indir_name, THE_INFILE) # out outdir_name = os.path.join(temp_dir, THE_OUTDIR) os.mkdir(outdir_name) outfile_name = os.path.join(outdir_name, THE_OUTFILE) # write infile infile = open(infile_name, 'w') input = to_string(input) infile.write(input) infile.close() # fix perms # TODO group permission should suffice os.chmod(temp_dir, 0755) # read os.chmod(indir_name, 0755) # read os.chmod(infile_name, 0755) # read os.chmod(outdir_name, 0777) # read / write properties = PropertyValue("Hidden", 0, True, 0), #import pdb;pdb.set_trace() doc = desktop.loadComponentFromURL("file://%s" % infile_name, "_blank", 0, properties) properties = (PropertyValue("Hidden", 0, True, 0), PropertyValue("FilterName", 0, out_filter, 0)) doc.storeToURL('file://%s' % outfile_name, tuple(properties)) out_f = open(outfile_name, 'r') output = out_f.read() # load other files (useful only for html) image_names = [ name for name in os.listdir(outdir_name) if name != THE_OUTFILE ] img_res = [] for image_name in image_names: img_res.append(os.path.join(outdir_name, image_name)) if unicode: output = output.decode('utf8') return output, img_res finally: end_processing() try: if out_f: out_f.close() if infile: infile.close() # Do not remove dir: we only return images path to avoid # mem overload # top = temp_dir # for root, dirs, files in os.walk(top, topdown=False): # for name in files: # os.remove(os.path.join(root, name)) # for name in dirs: # os.rmdir(os.path.join(root, name)) # os.rmdir(top) except: # TODO : warn pass
def createProp(name, value): """Creates an UNO property.""" prop = PropertyValue() prop.Name = name prop.Value = value return prop
def property_value(self, name, value): from com.sun.star.beans import PropertyValue pv = PropertyValue() pv.Name = name pv.Value = value return pv
local = uno.getComponentContext() resolver = local.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", local) context = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext") desktop = context.ServiceManager.createInstanceWithContext( "com.sun.star.frame.Desktop", context) url1 = "file://" + str(os.path.abspath(sys.argv[1])) url2 = "file://" + str(os.path.abspath(sys.argv[2])) #print ("First argument: %s" % str(sys.argv[1])) #print ("Second argument: %s" % str(sys.argv[2])) props = [] props.append(PropertyValue('ShowTrackedChanges', 0, True, DIRECT_VALUE)) document = desktop.loadComponentFromURL(url2, "_blank", 0, (tuple(props))) #frame = document.getCurrentController().getFrame() #frame = desktop.getCurrentFrame dispatcher = context.ServiceManager.createInstanceWithContext( "com.sun.star.frame.DispatchHelper", context) #dispatcher = context.ServiceManager.createInstance("com.sun.star.frame.DispatchHelper") dispatcher.executeDispatch(document.getCurrentController().getFrame(), ".uno:ShowTrackedChanges", "", 0, (tuple(props))) props[0] = PropertyValue('URL', 0, url1, DIRECT_VALUE) #props.append( PropertyValue('URL',0,url1,DIRECT_VALUE)) dispatcher.executeDispatch(document.getCurrentController().getFrame(), ".uno:CompareDocuments", "", 0, (tuple(props))) #dispatcher.executeDispatch(frame, ".uno:CompareDocuments", "", 0, (tuple(props)))