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 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
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 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': # Give some additional params if we need to open a CSV file prop2 = PropertyValue() prop2.Name = 'FilterFlags' prop2.Value = '59,34,76,1' #prop2.Name = 'FilterData' #prop2.Value = 'Any' props = (prop, prop2) else: props = (prop,) 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))
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))
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))
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 test_sequence(self): doc = self.get_doc() text = doc.getText() table = doc.createInstance("com.sun.star.text.TextTable") table.setName("NewTable") table.initialize(2, 2) text.insertTextContent(text.getEnd(), table, True) a = (("foo", "bar"), (1, 2)) table.setDataArray(a) data = table.getDataArray() self.assertEqual(data, a) from com.sun.star.beans import PropertyValue arg1 = PropertyValue() arg1.Name = "InputStream" arg2 = PropertyValue() arg2.Name = "FilterName" arg2.Value = "writer_web_HTML" bs = b"<html><body><p>Text from <b>HTML</b>.</p></body></html>" sequence = self.create("com.sun.star.io.SequenceInputStream") sequence.initialize((uno.ByteSequence(bs),)) arg1.Value = sequence text = doc.getText() text.setString("") text.getEnd().insertDocumentFromURL("", (arg1, arg2)) sequence.closeInput()
def make_prop(self, name, value): prop = PropertyValue() prop.Name = name if isinstance(value, (list, tuple)): prop.Value = uno.Any("[]com.sun.star.beans.PropertyValue", value) else: prop.Value = value return prop
def do_file(file, desktop): 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) file_save="%s.%s" % (file, extension) 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 ngw_mailmerge(filename_in, fields, target_dir): local = uno.getComponentContext() resolver = local.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", local) try: context = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;" "StarOffice.ComponentContext") except NoConnectException: print("Can't reach libreoffice on localhost on UDP port 2002") raise desktop = context.ServiceManager.createInstance( 'com.sun.star.frame.Desktop') document = desktop.loadComponentFromURL( uno.systemPathToFileUrl(filename_in), '_blank', 0, ()) find_replace = document.createSearchDescriptor() p1 = PropertyValue() p1.Name = 'SearchRegularExpression' p1.Value = True find_replace.setPropertyValue('SearchRegularExpression', True) find_replace.setSearchString('[{][{]([^}]*)[}][}]') found = document.findFirst(find_replace) while found: field_name = found.getString()[2:-2] found.setString(fields.get(field_name, 'FIELD NOT FOUND')) found = document.findNext(found.getEnd(), find_replace) oldumask = os.umask(0o007) filename_out = TMPDIR + '/' + get_outputprefix() + '.pdf' p1 = PropertyValue() p1.Name = 'Overwrite' p1.Value = True p2 = PropertyValue() p2.Name = 'FilterName' p2.Value = 'writer_pdf_Export' document.storeToURL(uno.systemPathToFileUrl(filename_out), (p1, p2)) document.dispose() os.umask(oldumask) basefilename_out = os.path.basename(filename_out) # move to final directory, overriding any permissions if subprocess.call([ "sudo", "/usr/bin/mvoomail", basefilename_out, target_dir]): print('File move failed') return None return basefilename_out
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, d): props = [] for key in d: prop = PropertyValue() prop.Name = key if isinstance(d[key], dict): prop.Value = uno.Any("[]com.sun.star.beans.PropertyValue", self._toProperties(d[key])) else: prop.Value = d[key] props.append(prop) return tuple(props)
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, dest_type, url_current, url_addition # doc_type # dest_type, # url_current, # 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 init_graphics(self, ctx, high_contrast=False): from com.sun.star.beans import PropertyValue from bookmarks import ICONS_DIR graphics = {} gp = ctx.getServiceManager().createInstanceWithContext( "com.sun.star.graphic.GraphicProvider", ctx) p = PropertyValue() p.Name = "URL" for graphic_def in self.GRAPHIC_DEFS: if high_contrast: p.Value = ICONS_DIR + graphic_def[1] + "_h.png" else: p.Value = ICONS_DIR + graphic_def[1] + ".png" graphics[graphic_def[0]] = gp.queryGraphic((p,)) self.graphics = graphics
def init_graphics(self, ctx, high_contrast=False): from com.sun.star.beans import PropertyValue from bookmarks import ICONS_DIR graphics = {} gp = ctx.getServiceManager().createInstanceWithContext( "com.sun.star.graphic.GraphicProvider", ctx) p = PropertyValue() p.Name = "URL" for graphic_def in self.GRAPHIC_DEFS: if high_contrast: p.Value = ICONS_DIR + graphic_def[1] + "_h.png" else: p.Value = ICONS_DIR + graphic_def[1] + ".png" graphics[graphic_def[0]] = gp.queryGraphic((p, )) self.graphics = graphics
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 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 load(self): names = [] for c in self.config_attrs: names.append((getattr(ConfigNames, c), c)) try: names.sort(key=operator.itemgetter(0)) except: _names = [(item[0], item) for item in names] _names.sort() names = [item for (key, item) in _names] config_provider = self.ctx.getServiceManager( ).createInstanceWithContext( 'com.sun.star.configuration.ConfigurationProvider', self.ctx) node = PropertyValue() node.Name = 'nodepath' node.Value = ConfigNames.config_node try: config_reader = config_provider.createInstanceWithArguments( 'com.sun.star.configuration.ConfigurationAccess', (node, )) config_values = config_reader.getPropertyValues( tuple([name[0] for name in names])) for k, v in zip([name[1] for name in names], config_values): setattr(Config, k, v) except: raise
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 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 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 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 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
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 __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 __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
def getPdfProps(): props = [] prop = PropertyValue() prop.Name = "FilterName" prop.Value = "writer_pdf_Export" props.append(prop) return tuple(props)
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 _createProperty(self, name, value): """Create property""" from com.sun.star.beans import PropertyValue property = PropertyValue() property.Name = name property.Value = value return property
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 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 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 trigger(self, args): # access the current writer document desktop = self.ctx.ServiceManager.createInstanceWithContext( "com.sun.star.frame.Desktop", self.ctx) model = desktop.getCurrentComponent() controller = model.getCurrentController() selection = controller.getSelection() if selection.supportsService( "com.sun.star.text.TextGraphicObject") and selection.getName(): img_name = selection.getName() # use tempfile to export graphic temp = tempfile.NamedTemporaryFile(delete=False) url_property = PropertyValue() url_property.Name = "URL" url_property.Value = "file:///" + temp.name # sadly, OutputStream doesn't work #stream_property = PropertyValue() #stream_property.Name = "OutputStream" #stream_property.Value = out_stream mime_property = PropertyValue() mime_property.Name = "MimeType" mime_property.Value = "image/png" graphic_provider = self.ctx.ServiceManager.createInstanceWithContext( "com.sun.star.graphic.GraphicProvider", self.ctx) graphic_provider.storeGraphic(selection.Graphic, (url_property, mime_property)) temp.close() img_data = open(temp.name, "rb").read() os.unlink(temp.name) img_metadata = get_image_metadata(self.ctx, model, img_name) img_transferable = ImageWithMetadataTransferable( img_data, img_metadata) self.clip_owner = ImageWithMetadataClipboardOwner() clip = self.ctx.ServiceManager.createInstanceWithContext( "com.sun.star.datatransfer.clipboard.SystemClipboard", self.ctx) clip.setContents(img_transferable, self.clip_owner)
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 _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 convertDocument(self): '''Calls OO to perform a document conversion. Note that the conversion is not really done if the source and target documents have the same type.''' properties = [] from com.sun.star.beans import PropertyValue prop = PropertyValue() prop.Name = 'FilterName' prop.Value = self.resultFilter properties.append(prop) if self.resultType == 'csv': # For CSV export, add options (separator, etc) optionsProp = PropertyValue() optionsProp.Name = 'FilterOptions' optionsProp.Value = '59,34,76,1' properties.append(optionsProp) self.doc.storeToURL(self.resultUrl, tuple(properties))
def to_tuple(args: Dict[str, Any]) -> Tuple[Any, ...]: ret = [] for arg_key, arg_value in args.items(): value = PropertyValue() value.Name = arg_key value.Value = arg_value ret.append(value) return tuple(ret)
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 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 _toProperties(self, dict): props = [] for key in dict: prop = PropertyValue() prop.Name = key prop.Value = dict[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 property_tuple(self, propDict): properties = [] for k, v in propDict.items(): property = PropertyValue() property.Name = k property.Value = v properties.append(property) return tuple(properties)
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 _unoProps(**args): props = [] for key in args: prop = PropertyValue() prop.Name = key prop.Value = args[key] props.append(prop) return tuple(props)
def UnoProps(**args): props = [] for key in args: prop = PropertyValue() prop.Name = key prop.Value = args[key] props.append(prop) return tuple(props)
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 convertDocument(self): '''Calls OO to perform a document conversion. Note that the conversion is not really done if the source and target documents have the same type.''' properties = [] from com.sun.star.beans import PropertyValue prop = PropertyValue() prop.Name = 'FilterName' prop.Value = self.resultFilter properties.append(prop) if self.resultType == 'csv': # For CSV export, add options (separator, etc) optionsProp = PropertyValue() optionsProp.Name = 'FilterOptions' optionsProp.Value = '59,34,76,1' properties.append(optionsProp) self.doc.storeToURL(self.resultUrl, tuple(properties))
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 proofread(nDocId, TEXT, LOCALE, nStartOfSentencePos, nSuggestedSentenceEndPos, rProperties): global ignore aErrs = [] s = TEXT[nStartOfSentencePos:nSuggestedSentenceEndPos] for i in get_rule(LOCALE).dic: # 0: regex, 1: replacement, 2: message, 3: condition, 4: ngroup, (5: oldline), 6: case sensitive ? if i[0] and not str(i[0]) in ignore: for m in i[0].finditer(s): try: if not i[3] or eval(i[3]): aErr = uno.createUnoStruct( "com.sun.star.linguistic2.SingleProofreadingError") aErr.nErrorStart = nStartOfSentencePos + m.start( i[4]) # nStartOfSentencePos aErr.nErrorLength = m.end(i[4]) - m.start(i[4]) aErr.nErrorType = PROOFREADING aErr.aRuleIdentifier = str(i[0]) iscap = (i[-1] and m.group(i[4])[0:1].isupper()) if i[1][0:1] == "=": aErr.aSuggestions = tuple( cap( eval(i[1][1:]).replace('|', "\n").split("\n"), iscap, LOCALE)) elif i[1] == "_": aErr.aSuggestions = () else: aErr.aSuggestions = tuple( cap( m.expand(i[1]).replace('|', "\n").split("\n"), iscap, LOCALE)) comment = i[2] if comment[0:1] == "=": comment = eval(comment[1:]) else: comment = m.expand(comment) aErr.aShortComment = comment.replace( '|', '\n').replace('\\n', '\n').split("\n")[0].strip() aErr.aFullComment = comment.replace('|', '\n').replace( '\\n', '\n').split("\n")[-1].strip() if "://" in aErr.aFullComment: p = PropertyValue() p.Name = "FullCommentURL" p.Value = aErr.aFullComment aErr.aFullComment = aErr.aShortComment aErr.aProperties = (p, ) else: aErr.aProperties = () aErrs = aErrs + [aErr] except Exception as e: if len(i) == 7: raise Exception(str(e), i[5]) raise return tuple(aErrs)
def to_tuple(args: Dict[str, Any]) -> Tuple[Any, ...]: """Turns a dict into a tuple of name-value pairs.""" ret = [] for arg_key, arg_value in args.items(): value = PropertyValue() value.Name = arg_key value.Value = arg_value ret.append(value) return tuple(ret)
def _getOptionsReader(self): smgr = self.ctx.getServiceManager() cfg = smgr.createInstanceWithContext( 'com.sun.star.configuration.ConfigurationProvider', self.ctx) node = PropertyValue() node.Name = 'nodepath' node.Value = '/org.parlatype.config' return cfg.createInstanceWithArguments( 'com.sun.star.configuration.ConfigurationAccess', (node,))
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 __setProperties(self, properties): for p in ["IsSpellWithDigits", "IsSpellUpperCase", "HyphMinLeading", "HyphMinTrailing", "HyphMinWordLength"]: pValue = PropertyValue() pValue.Name = p try: pValue.Value = properties.getPropertyValue(p) self.setValue(pValue) except Exception as e: logging.exception("Exception setting property value '%s'", p)
def jumpFreeze(*args): args = [''] args[0] = PropertyValue() # Default constructor args[0].Name = "Nr" args[0].Value = 2 call_dispatch(doc, '.uno:JumpToTable', args) call_dispatch(doc, '.uno:FreezePanesFirstRow')
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)