def convert_file(self, file_name, filters, timeout=300): fd, output_filename = mkstemp(suffix='.pdf') os.close(fd) file_name = os.path.abspath(file_name) input_url = uno.systemPathToFileUrl(file_name) output_url = uno.systemPathToFileUrl(output_filename) # Trigger SIGALRM after the timeout has passed. signal.signal(signal.SIGALRM, handle_timeout) signal.alarm(timeout) try: doc = self.open_document(input_url, filters) for (service, pdf) in self.PDF_FILTERS: if doc.supportsService(service): prop = self.property_tuple({ "FilterName": pdf, "MaxImageResolution": 300, "SelectPdfVersion": 1, }) doc.storeToURL(output_url, prop) doc.close(True) return output_filename raise ConversionFailure("Cannot export to PDF") except Exception: os.unlink(output_filename) raise finally: signal.alarm(0)
def convert(self, inputFile, outputFile): """ Convert the input file (a spreadsheet) to a CSV file. """ # Start openoffice if needed. if not self.desktop: if not self.oorunner: self.oorunner = ooutils.OORunner() self.desktop = self.oorunner.connect() inputUrl = uno.systemPathToFileUrl(os.path.abspath(inputFile)) outputUrl = uno.systemPathToFileUrl(os.path.abspath(outputFile)) document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, ooutils.oo_properties(Hidden=True)) try: # Additional property option: # FilterOptions="59,34,0,1" # 59 - Field separator (semicolon), this is the ascii value. # 34 - Text delimiter (double quote), this is the ascii value. # 0 - Character set (system). # 1 - First line number to export. # # For more information see: # http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options # document.storeToURL(outputUrl, ooutils.oo_properties(FilterName="Text - txt - csv (StarCalc)")) finally: document.close(True)
def convert_file(self, file_name, out_file, filters, timeout=300): timer = Timer(timeout, self.terminate) timer.start() try: desktop = self.connect() if desktop is None: raise RuntimeError("Cannot connect to LibreOffice.") file_name = os.path.abspath(file_name) input_url = uno.systemPathToFileUrl(file_name) for filter_name in filters: props = self.get_input_properties(filter_name) doc = desktop.loadComponentFromURL(input_url, '_blank', 0, props) # noqa if doc is None: continue if hasattr(doc, 'refresh'): doc.refresh() output_url = uno.systemPathToFileUrl(out_file) prop = self.get_output_properties(doc) doc.storeToURL(output_url, prop) doc.dispose() doc.close(True) del doc finally: timer.cancel()
def __call__(self, xsl_path, inp_path, out_path): import uno import unohelper import os.path from hwp5.plat._uno import ucb from hwp5.plat._uno.adapters import OutputStreamToFileLike xsl_path = os.path.abspath(xsl_path) xsl_url = uno.systemPathToFileUrl(xsl_path) inp_path = os.path.abspath(inp_path) inp_url = uno.systemPathToFileUrl(inp_path) inp_stream = ucb.open_url(self.context, inp_url) out_path = os.path.abspath(out_path) with file(out_path, 'w') as out_file: out_stream = OutputStreamToFileLike(out_file, dontclose=True) from com.sun.star.io import XStreamListener class XSLTListener(unohelper.Base, XStreamListener): def __init__(self): self.event = OneshotEvent() def started(self): logger.info('XSLT started') def closed(self): logger.info('XSLT closed') self.event.signal() def terminated(self): logger.info('XSLT terminated') self.event.signal() def error(self, exception): logger.error('XSLT error: %s', exception) self.event.signal() def disposing(self, source): logger.info('XSLT disposing: %s', source) self.event.signal() listener = XSLTListener() transformer = XSLTTransformer(self.context, xsl_url, '', '') transformer.InputStream = inp_stream transformer.OutputStream = out_stream transformer.addListener(listener) transformer.start() import os.path xsl_name = os.path.basename(xsl_path) logger.info('xslt.soffice(%s) start', xsl_name) try: listener.event.wait() finally: logger.info('xslt.soffice(%s) end', xsl_name) transformer.removeListener(listener) return dict()
def _timed_convert_file(self, file_name): desktop = self.connect() self.check_desktop(desktop) # log.debug("[%s] connected.", file_name) try: url = uno.systemPathToFileUrl(file_name) props = self.property_tuple({ "Hidden": True, "MacroExecutionMode": 0, "ReadOnly": True, "Overwrite": True, "OpenNewView": True, "StartPresentation": False, "RepairPackage": False, }) doc = desktop.loadComponentFromURL(url, "_blank", 0, props) except IllegalArgumentException: raise ConversionFailure("Cannot open document.") except DisposedException: raise SystemFailure("Bridge is disposed.") if doc is None: raise ConversionFailure("Cannot open document.") # log.debug("[%s] opened.", file_name) try: try: doc.ShowChanges = False except AttributeError: pass try: doc.refresh() except AttributeError: pass output_url = uno.systemPathToFileUrl(OUT_FILE) prop = self.get_output_properties(doc) # log.debug("[%s] refreshed.", file_name) doc.storeToURL(output_url, prop) # log.debug("[%s] exported.", file_name) doc.dispose() doc.close(True) del doc # log.debug("[%s] closed.", file_name) except ( DisposedException, IOException, CannotConvertException, RuntimeException, ): raise ConversionFailure("Cannot generate PDF.") stat = os.stat(OUT_FILE) if stat.st_size == 0 or not os.path.exists(OUT_FILE): raise ConversionFailure("Cannot generate PDF.") return OUT_FILE
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 convert_file(self, file_name, timeout): timer = Timer(timeout, self.terminate) timer.start() try: desktop = self.connect() if desktop is None: raise SystemFailure('Cannot connect to LibreOffice.') url = uno.systemPathToFileUrl(file_name) props = self.property_tuple({ 'Hidden': True, 'MacroExecutionMode': 0, 'ReadOnly': True, 'Overwrite': True, }) try: doc = desktop.loadComponentFromURL(url, '_blank', 0, props) except IllegalArgumentException: raise ConversionFailure('Cannot open document.') except DisposedException: raise SystemFailure('Bridge is disposed.') if doc is None: raise ConversionFailure('Cannot open document.') try: doc.ShowChanges = False except AttributeError: pass try: doc.refresh() except AttributeError: pass try: extension = file_name.split('.', 1)[1] output_url = uno.systemPathToFileUrl( file_name.replace(extension, 'pdf')) self.OUT = file_name.replace(extension, 'pdf') prop = self.get_output_properties(doc) doc.storeToURL(output_url, prop) doc.dispose() doc.close(True) del doc except DisposedException: raise ConversionFailure('Cannot generate PDF.') stat = os.stat(self.OUT) if stat.st_size == 0 or not os.path.exists(self.OUT): raise ConversionFailure('Cannot generate PDF.') finally: timer.cancel()
def run(source, update, pdf): fileUrl = uno.systemPathToFileUrl(os.path.realpath(source)) filepath, ext = os.path.splitext(source) fileUrlPDF = uno.systemPathToFileUrl(os.path.realpath(filepath + ".pdf")) runner = OORunner(2002) desktop, dispatcher = runner.connect() print("Loading document") struct = uno.createUnoStruct('com.sun.star.beans.PropertyValue') struct.Name = 'Hidden' struct.Value = True document = desktop.loadComponentFromURL(fileUrl, "_default", 0, ([struct])) doc = document.getCurrentController() #doc = desktop.getCurrentComponent().getCurrentController() if update: print("Updating Indexes and Saving") dispatcher.executeDispatch(doc, ".uno:UpdateAllIndexes", "", 0, ()) # Saving opts = [] if ext == ".docx": struct = uno.createUnoStruct('com.sun.star.beans.PropertyValue') struct.Name = "FilterName" struct.Value = "MS Word 2007 XML" opts.append(struct) struct = uno.createUnoStruct('com.sun.star.beans.PropertyValue') struct.Name = 'URL' struct.Value = fileUrl opts.append(struct) dispatcher.executeDispatch(doc, ".uno:SaveAs", "", 0, tuple(opts)) if pdf: print("Generating PDF") struct = uno.createUnoStruct('com.sun.star.beans.PropertyValue') struct.Name = 'URL' struct.Value = fileUrlPDF struct2 = uno.createUnoStruct('com.sun.star.beans.PropertyValue') struct2.Name = "FilterName" struct2.Value = "writer_pdf_Export" dispatcher.executeDispatch(doc, ".uno:ExportDirectToPDF", "", 0, tuple([struct, struct2])) runner.shutdown()
def create_thumbnails(self): """ Create thumbnail images for presentation. """ log.debug('create thumbnails OpenOffice') if self.check_thumbnails(): return if is_win(): thumb_dir_url = 'file:///' + self.get_temp_folder().replace('\\', '/') \ .replace(':', '|').replace(' ', '%20') else: thumb_dir_url = uno.systemPathToFileUrl(self.get_temp_folder()) properties = [] properties.append(self.create_property('FilterName', 'impress_png_Export')) properties = tuple(properties) doc = self.document pages = doc.getDrawPages() if not pages: return if not os.path.isdir(self.get_temp_folder()): os.makedirs(self.get_temp_folder()) for index in range(pages.getCount()): page = pages.getByIndex(index) doc.getCurrentController().setCurrentPage(page) url_path = '%s/%s.png' % (thumb_dir_url, str(index + 1)) path = os.path.join(self.get_temp_folder(), str(index + 1) + '.png') try: doc.storeToURL(url_path, properties) self.convert_thumbnail(path, index + 1) delete_file(path) except ErrorCodeIOException as exception: log.exception('ERROR! ErrorCodeIOException %d' % exception.ErrCode) except: log.exception('%s - Unable to store openoffice preview' % path)
def open( self, filename ): """Open an OpenOffice document""" #http://www.oooforum.org/forum/viewtopic.phtml?t=35344 properties = [] properties.append( OpenOfficeDocument._makeProperty( 'Hidden', True ) ) properties = tuple( properties ) self.oodocument = self.openoffice.loadComponentFromURL( uno.systemPathToFileUrl( os.path.abspath( filename ) ), "_blank", 0, properties )
def save(self, path, filetype=None): IOException = uno.getClass('com.sun.star.io.IOException') # UNO requires absolute paths url = uno.systemPathToFileUrl(os.path.abspath(path)) # Filters used when saving document. # https://github.com/LibreOffice/core/tree/330df37c7e2af0564bcd2de1f171bed4befcc074/filter/source/config/fragments/filters filetypes = dict( jpg='calc_jpg_Export', pdf='calc_pdf_Export', png='calc_png_Export', svg='calc_svg_Export', xls='Calc MS Excel 2007 XML', xlsx='Calc MS Excel 2007 XML Template', ) if filetype: filter = uno.createUnoStruct('com.sun.star.beans.PropertyValue') filter.Name = 'FilterName' filter.Value = filetypes[filetype] filters = (filter, ) else: filters = () try: self.document.storeToURL(url, filters) except IOException as e: raise IOError(e.Message)
def load_presentation(self): """ Called when a presentation is added to the SlideController. It builds the environment, starts communcations with the background OpenOffice task started earlier. If OpenOffice is not present is is started. Once the environment is available the presentation is loaded and started. """ log.debug('Load Presentation OpenOffice') if is_win(): desktop = self.controller.get_com_desktop() if desktop is None: self.controller.start_process() desktop = self.controller.get_com_desktop() url = 'file:///' + self.file_path.replace('\\', '/').replace( ':', '|').replace(' ', '%20') else: desktop = self.controller.get_uno_desktop() url = uno.systemPathToFileUrl(self.file_path) if desktop is None: return False self.desktop = desktop properties = [] properties.append(self.create_property('Hidden', True)) properties = tuple(properties) try: self.document = desktop.loadComponentFromURL( url, '_blank', 0, properties) except: log.warning('Failed to load presentation %s' % url) return False self.presentation = self.document.getPresentation() self.presentation.Display = ScreenList().current['number'] + 1 self.control = None self.create_thumbnails() self.create_titles_and_notes() return True
def create_thumbnails(self): """ Create thumbnail images for presentation """ log.debug(u'create thumbnails OpenOffice') if self.check_thumbnails(): return if os.name == u'nt': thumbdirurl = u'file:///' + self.get_temp_folder().replace(u'\\', u'/') \ .replace(u':', u'|').replace(u' ', u'%20') else: thumbdirurl = uno.systemPathToFileUrl(self.get_temp_folder()) props = [] props.append(self.create_property(u'FilterName', u'impress_png_Export')) props = tuple(props) doc = self.document pages = doc.getDrawPages() if not pages: return if not os.path.isdir(self.get_temp_folder()): os.makedirs(self.get_temp_folder()) for idx in range(pages.getCount()): page = pages.getByIndex(idx) doc.getCurrentController().setCurrentPage(page) urlpath = u'%s/%s.png' % (thumbdirurl, unicode(idx + 1)) path = os.path.join(self.get_temp_folder(), unicode(idx + 1) + u'.png') try: doc.storeToURL(urlpath, props) self.convert_thumbnail(path, idx + 1) delete_file(path) except ErrorCodeIOException, exception: log.exception(u'ERROR! ErrorCodeIOException %d' % exception.ErrCode) except:
def save(): """Сохранить настройки. Записать параметры работы в файл. """ doc = XSCRIPTCONTEXT.getDocument() serviceManager = XSCRIPTCONTEXT.getComponentContext().ServiceManager fileAccess = serviceManager.createInstance( "com.sun.star.ucb.SimpleFileAccess" ) configPathUrl = "vnd.sun.star.tdoc:/{}/Scripts/python/".format(doc.RuntimeUID) if not fileAccess.exists(configPathUrl): fileAccess.createFolder(configPathUrl) configFileUrl = configPathUrl + "settings.ini" tempFile = tempfile.NamedTemporaryFile( mode="wt", encoding="UTF-8", delete=False ) tempFileUrl = uno.systemPathToFileUrl(tempFile.name) with tempFile: SETTINGS.write(tempFile) fileAccess.copy(tempFileUrl, configFileUrl) fileAccess.kill(tempFileUrl)
def save_active_doc_with_timestamp(args): """Save the Active Document with new current timeStamp.""" print("-" * 42) print("save_active_doc_with_timestamp:") doc = get_current_document() filename_full_path = uno.fileUrlToSystemPath(doc.URL) print("filename_full_path:") print(filename_full_path) print("", filename_full_path) # so extract the FileName from the path_full path_full = os.path.dirname(filename_full_path) filename = os.path.basename(filename_full_path) file_basename = os.path.splitext(filename)[0] file_ext = os.path.splitext(filename)[1] # print("doc_name: " + doc_name) file_basename_new = update_timestamp(file_basename) if file_basename_new: # put together new filename_full_path_new filename_full_path_new = path_full + "/" + file_basename_new + file_ext print("filename_full_path_new:") print(filename_full_path_new) # https://wiki.openoffice.org/wiki/Documentation/DevGuide/OfficeDev/Storing_Documents doc.storeAsURL(uno.systemPathToFileUrl(filename_full_path_new), ()) else: info = "no timestamp found in filename - so i can't update it." print(info) msgbox(info) print("-" * 42)
def xslt_with_libreoffice(xsl_path, inp_path, out_path): import os.path xsl_path = os.path.abspath(xsl_path) xsl_name = os.path.basename(xsl_path) xsl_url = uno.systemPathToFileUrl(xsl_path) inp_path = os.path.abspath(inp_path) inp_file = file(inp_path) inp_strm = InputStreamFromFileLike(inp_file, dontclose=True) out_path = os.path.abspath(out_path) out_file = file(out_path, 'w') out_strm = OutputStreamToFileLike(out_file, dontclose=True) transformer = XSLTTransformer(xsl_url, '', '') transformer.InputStream = inp_strm transformer.OutputStream = out_strm listener = XSLTListener() transformer.addListener(listener) transformer.start() logger.info('xslt.soffice(%s) start', xsl_name) try: listener.event.wait() finally: logger.info('xslt.soffice(%s) end', xsl_name) transformer.removeListener(listener) return dict()
def extract_thumbnails(self, temp_folder): """ Create thumbnails for the presentation """ thumbnails = [] thumb_dir_url = uno.systemPathToFileUrl(temp_folder) properties = (self._create_property('FilterName', 'impress_png_Export'),) pages = self._document.getDrawPages() if not pages: return [] if not os.path.isdir(temp_folder): os.makedirs(temp_folder) for index in range(pages.getCount()): page = pages.getByIndex(index) self._document.getCurrentController().setCurrentPage(page) url_path = '{path}/{name}.png'.format(path=thumb_dir_url, name=str(index + 1)) path = os.path.join(temp_folder, str(index + 1) + '.png') try: self._document.storeToURL(url_path, properties) thumbnails.append(path) except ErrorCodeIOException as exception: log.exception('ERROR! ErrorCodeIOException {error:d}'.format(error=exception.ErrCode)) except Exception: log.exception('{path} - Unable to store openoffice preview'.format(path=path)) return thumbnails
def getResultUrl(self): '''Returns the path of the result file in the format needed by OO. If the result type and the input type are the same (ie the user wants to refresh indexes or some other action and not perform a real conversion), the result file is named <inputFileName>.res.<resultType>. Else, the result file is named like the input file but with a different extension: <inputFileName>.<resultType> ''' import uno baseName = os.path.splitext(self.docPath)[0] if self.resultType != self.inputType: res = '%s.%s' % (baseName, self.resultType) else: res = '%s.res.%s' % (baseName, self.resultType) try: f = open(res, 'w') f.write('Hello') f.close() os.remove(res) return uno.systemPathToFileUrl(res) except (OSError, IOError), ioe: raise ConverterError(CANNOT_WRITE_RESULT % (res, ioe))
def create_thumbnails(self): """ Create thumbnail images for presentation. """ log.debug('create thumbnails OpenOffice') if self.check_thumbnails(): return if os.name == 'nt': thumb_dir_url = 'file:///' + self.get_temp_folder().replace('\\', '/') \ .replace(':', '|').replace(' ', '%20') else: thumb_dir_url = uno.systemPathToFileUrl(self.get_temp_folder()) properties = [] properties.append(self.create_property('FilterName', 'impress_png_Export')) properties = tuple(properties) doc = self.document pages = doc.getDrawPages() if not pages: return if not os.path.isdir(self.get_temp_folder()): os.makedirs(self.get_temp_folder()) for index in range(pages.getCount()): page = pages.getByIndex(index) doc.getCurrentController().setCurrentPage(page) url_path = '%s/%s.png' % (thumb_dir_url, str(index + 1)) path = os.path.join(self.get_temp_folder(), str(index + 1) + '.png') try: doc.storeToURL(url_path, properties) self.convert_thumbnail(path, index + 1) delete_file(path) except ErrorCodeIOException as exception: log.exception('ERROR! ErrorCodeIOException %d' % exception.ErrCode) except: log.exception('%s - Unable to store openoffice preview' % path)
def userExist(self, username, partid, email): uri = "/FluxBB/router/index.php/getdata/checkifuserexist/%s/%s/%s" uri = uri % (username, partid, email) uri = uno.systemPathToFileUrl(uri) self.__conn.request('GET', uri) response = self.__conn.getresponse() return json.loads(response.read().decode())
def load_presentation(self, file_path, screen_number): """ Load a presentation """ self._file_path = file_path url = uno.systemPathToFileUrl(file_path) properties = (self._create_property('Hidden', True),) self._document = None loop_count = 0 while loop_count < 3: try: self._document = self.desktop.loadComponentFromURL(url, '_blank', 0, properties) except Exception: log.exception('Failed to load presentation {url}'.format(url=url)) if self._document: break time.sleep(0.5) loop_count += 1 if loop_count == 3: log.error('Looped too many times') return False self._presentation = self._document.getPresentation() self._presentation.Display = screen_number self._control = None return True
def addNewUser(self, username, partid, email): uri = "/FluxBB/router/index.php/getdata/addnewndcuser/%s/%s/%s" uri = uri % (username, partid, email) uri = uno.systemPathToFileUrl(uri) self.__conn.request('GET', uri, None, self.secureKey()) response = self.__conn.getresponse() return response.status == 200
def getTopicStatusList(self, uname, depart, email): import uno uri = "/FluxBB/router/index.php/getdata/gettopicofuser/%s/%s/%s" uri = uri % (uname.strip(), email.strip(), depart.strip()) uri = uno.systemPathToFileUrl(uri) self.__conn.request('GET', uri) response = self.__conn.getresponse() jdatas = json.loads(response.read().decode('utf-8'))['aaData'] lsts = list() for data in jdatas: data[2] = int(data[2]) data[3] = int(data[3]) title = '錯誤!' # @TODO: 以實際 post 數量代替 num_replies # creator = 0 AND num_replies=0 LEVEL_CREATE if data[2] == 0: # and data[3] == 0: title = '已收到' # creator>1 AND num_replies=0 LEVEL_ASSIGN if data[2] > 1 and data[3] == 0: title = '處理中' # creator>1 AND num_replies>0 LEVEL_REPLY if data[2] > 1 and data[3] > 0: title = '處理中' if data[2] == 1: # LEVEL_DONE title = '已審核' lsts.append([data[1], title, data[0], data[2], data[4]]) return lsts
def test1_currentdoc(self): """Test the current document button.""" def useDialog(innerSelf): innerSelf.evtHandler.actionPerformed(MyActionEvent("UseCurrent")) testutil.clear_messages_sent() self.runDlg(useDialog) self.assertEqual(len(testutil.messages_sent), 1) self.assertEqual(testutil.messages_sent[0][0], "Please save the current document first.") self.assertEqual(self.dlg.dlgCtrls.fileControl.getText(), "") with self.assertRaises(exceptions.ChoiceProblem): itemPos = dutil.get_selected_index( self.dlg.dlgCtrls.listboxFileType) OUT_FILEPATH = os.path.join(util.BASE_FOLDER, "temp.odt") OUT_FILEURL = uno.systemPathToFileUrl(OUT_FILEPATH) self.unoObjs.document.storeAsURL(OUT_FILEURL, ()) testutil.clear_messages_sent() self.runDlg(useDialog) self.assertEqual(len(testutil.messages_sent), 0) self.assertEqual(self.dlg.dlgCtrls.fileControl.getText(), OUT_FILEPATH) try: itemPos = dutil.get_selected_index( self.dlg.dlgCtrls.listboxFileType) self.assertEqual(itemPos, 0) except exceptions.ChoiceProblem: self.fail("Expected an item to be selected.")
def load_presentation(self): """ Called when a presentation is added to the SlideController. It builds the environment, starts communcations with the background OpenOffice task started earlier. If OpenOffice is not present is is started. Once the environment is available the presentation is loaded and started. """ log.debug('Load Presentation OpenOffice') if is_win(): desktop = self.controller.get_com_desktop() if desktop is None: self.controller.start_process() desktop = self.controller.get_com_desktop() url = 'file:///' + self.file_path.replace('\\', '/').replace(':', '|').replace(' ', '%20') else: desktop = self.controller.get_uno_desktop() url = uno.systemPathToFileUrl(self.file_path) if desktop is None: return False self.desktop = desktop properties = [] properties.append(self.create_property('Hidden', True)) properties = tuple(properties) try: self.document = desktop.loadComponentFromURL(url, '_blank', 0, properties) except: log.warning('Failed to load presentation %s' % url) return False self.presentation = self.document.getPresentation() self.presentation.Display = ScreenList().current['number'] + 1 self.control = None self.create_thumbnails() self.create_titles_and_notes() return True
def _timed_convert_file(self, file_name): desktop = self.connect() self.check_health(desktop) try: url = uno.systemPathToFileUrl(file_name) props = self.property_tuple({ 'Hidden': True, 'MacroExecutionMode': 0, 'ReadOnly': True, 'Overwrite': True, 'OpenNewView': True, 'StartPresentation': False, 'RepairPackage': False, }) doc = desktop.loadComponentFromURL(url, '_blank', 0, props) except IllegalArgumentException: raise ConversionFailure('Cannot open document.') except DisposedException: raise SystemFailure('Bridge is disposed.') if doc is None: raise ConversionFailure('Cannot open document.') try: try: doc.ShowChanges = False except AttributeError: pass try: doc.refresh() except AttributeError: pass output_url = uno.systemPathToFileUrl(OUT_FILE) prop = self.get_output_properties(doc) doc.storeToURL(output_url, prop) doc.dispose() doc.close(True) del doc except DisposedException: raise ConversionFailure('Cannot generate PDF.') stat = os.stat(OUT_FILE) if stat.st_size == 0 or not os.path.exists(OUT_FILE): raise ConversionFailure('Cannot generate PDF.') return OUT_FILE
def write_wordlist_file(self, FILEPATH): props = ( util.createProp('FilterName', 0), util.createProp('Overwrite', 1), ) wordListDoc = self.unoObjs.getOpenDocs(util.UnoObjs.DOCTYPE_CALC)[0] wordListDoc.document.storeAsURL(uno.systemPathToFileUrl(FILEPATH), props) return wordListDoc
def register_db(self, ods_path, db_path, db_name): if os.path.isfile(db_path): return if self.db_ctx.hasByName(db_name): raise ValueError("The database {} already exists.".format(db_name)) db_folder_path = os.path.dirname(ods_path) db_url = uno.systemPathToFileUrl(db_path) db_folder_url = uno.systemPathToFileUrl(db_folder_path) data_src = self.smgr.createInstanceWithContext( "com.sun.star.sdb.DataSource", self.ctx) data_src.URL = "sdbc:calc:" + ods_path data_src.DatabaseDocument.storeAsURL(db_url, ()) self.db_ctx.registerObject(db_name, data_src) data_src.DatabaseDocument.close(True)
def addDocumentToEnd( self, documentUrl, pageBreak=True ): cursor = self.oodocument.Text.createTextCursor() if cursor: cursor.gotoEnd( False ) if pageBreak: cursor.BreakType = PAGE_AFTER cursor.insertDocumentFromURL( uno.systemPathToFileUrl( os.path.abspath( documentUrl ) ), () ) return True return False
def saveAs( self, filename ): """Save the open office document to a new file, and possibly filetype. The type of document is parsed out of the file extension of the filename given.""" filename = uno.systemPathToFileUrl( os.path.abspath( filename ) ) #filterlist: http://wiki.services.openoffice.org/wiki/Framework/Article/Filter/FilterList_OOo_3_0 exportFilter = self._getExportFilter( filename ) props = exportFilter, #storeToURL: #http://codesnippets.services.openoffice.org/Office/Office.ConvertDocuments.snip self.oodocument.storeToURL( filename, props )
def test_searchAndCursor(self): ood = WriterDocument() ood.open("%s/docs/find_replace.odt" % self.path) search = ood.oodocument.createSearchDescriptor() search.setSearchString("search") result = ood.oodocument.findFirst(search) path = uno.systemPathToFileUrl("%s/docs/insertme.html" % self.path) result.insertDocumentFromURL(path, tuple()) ood.saveAs("%s/docs/docInTheMiddle.pdf" % self.path) ood.close()
def getInputUrls(self, docPath): '''Returns the absolute path of the input file. In fact, it returns a tuple with some URL version of the path for OO as the first element and the absolute path as the second element.''' import uno if not os.path.exists(docPath) and not os.path.isfile(docPath): raise ConverterError(DOC_NOT_FOUND % docPath) docAbsPath = os.path.abspath(docPath) # Return one path for OO, one path for me. return uno.systemPathToFileUrl(docAbsPath), docAbsPath
def compare(self, path, original_path, save_path): if not os.path.exists(path): raise DocumentCompareException("%s does not exist" % (path,)) url = uno.systemPathToFileUrl(path) if not os.path.exists(original_path): raise DocumentCompareException("%s does not exist" % (original_path,)) url_original = uno.systemPathToFileUrl(original_path) url_save = uno.systemPathToFileUrl(save_path) ### Load document p = PropertyValue() p.Name = "Hidden" p.Value = True properties = (p,) doc = self.desktop.loadComponentFromURL(url, "_blank", 0, properties) ### Compare with original document properties = [] p = PropertyValue() p.Name = "URL" p.Value = url_original properties.append(p) properties = tuple(properties) dispatch_helper = self.servicemanager.createInstanceWithContext( "com.sun.star.frame.DispatchHelper", self.context) dispatch_helper.executeDispatch(doc.getCurrentController().getFrame(), ".uno:CompareDocuments", "", 0, properties) ### Save File p = PropertyValue() p.Name = "Overwrite" p.Value = True properties = (p,) doc.storeToURL(url_save, properties) doc.dispose()
def compare(self, path, original_path, save_path): if not os.path.exists(path): raise DocumentCompareException("%s does not exist" % (path, )) url = uno.systemPathToFileUrl(path) if not os.path.exists(original_path): raise DocumentCompareException("%s does not exist" % (original_path, )) url_original = uno.systemPathToFileUrl(original_path) url_save = uno.systemPathToFileUrl(save_path) ### Load document p = PropertyValue() p.Name = "Hidden" p.Value = True properties = (p, ) doc = self.desktop.loadComponentFromURL(url, "_blank", 0, properties) ### Compare with original document properties = [] p = PropertyValue() p.Name = "URL" p.Value = url_original properties.append(p) properties = tuple(properties) dispatch_helper = self.servicemanager.createInstanceWithContext( "com.sun.star.frame.DispatchHelper", self.context) dispatch_helper.executeDispatch(doc.getCurrentController().getFrame(), ".uno:CompareDocuments", "", 0, properties) ### Save File p = PropertyValue() p.Name = "Overwrite" p.Value = True properties = (p, ) doc.storeToURL(url_save, properties) doc.dispose()
def save(self, path): from tools import Tools if not hasattr(self.document, 'getArgs'): return False # import_extension = self.imp[self.filter] if len(self.properties) == 0: export_extension = Tools.get_extension(path) properties = self.export_options[export_extension] self.set_properties(properties) self.document.storeToURL(uno.systemPathToFileUrl(abspath(path)), tuple(self.properties)) return True
def writer_image_insert_from_file(model, file_path): fileURL = uno.systemPathToFileUrl(file_path) text = model.getText() oCursor = text.createTextCursor() oGraph = model.createInstance("com.sun.star.text.GraphicObject") oGraph.GraphicURL = fileURL oGraph.AnchorType = AS_CHARACTER # Set the image size. oGraph.Width = 10000 oGraph.Height = 8000 text.insertTextContent(oCursor, oGraph, False)
def save(self, path, file_format='MS Word 97'): properties = ( PropertyValue("FilterName", 0, file_format, 0), PropertyValue("Overwrite", 0, True, 0)) if self.document: try: self.document.storeToURL(uno.systemPathToFileUrl(path), properties) except ErrorCodeIOException: self.errors.append("Save file error (may be already open): %s" % path) raise ODTFileError
def searchAndReplaceWithDocument( self, phrase, documentPath, regex=False ): #http://api.openoffice.org/docs/DevelopersGuide/Text/Text.xhtml#1_3_1_1_Editing_Text #cursor = self.oodocument.Text.createTextCursor() #http://api.openoffice.org/docs/DevelopersGuide/Text/Text.xhtml#1_3_3_3_Search_and_Replace search = self.oodocument.createSearchDescriptor() search.setSearchString( phrase ) search.SearchRegularExpression = regex result = self.oodocument.findFirst( search ) path = uno.systemPathToFileUrl( os.path.abspath( documentPath ) ) #http://api.openoffice.org/docs/DevelopersGuide/Text/Text.xhtml#1_3_1_5_Inserting_Text_Files return result.insertDocumentFromURL( path, tuple() )
def oeffne_text(self,pfad_translation): if self.mb.debug: log(inspect.stack) prop = uno.createUnoStruct("com.sun.star.beans.PropertyValue") prop.Name = 'Hidden' prop.Value = True url = uno.systemPathToFileUrl(pfad_translation) self.ooo = self.mb.doc.CurrentController.Frame.loadComponentFromURL(url,'_blank',0,(prop,)) return self.ooo.Text
def convert(self, inputFile, outputFile, SheetName = None, DelimiterInAscii = 9): """ Convert the input file (a spreadsheet) to a CSV file. @param DelimiterInAscii: the delimiter. Default value \t (Ascii: 9) """ # Start openoffice if needed. if not self.desktop: if not self.oorunner: self.oorunner = ooutils.OORunner() self.desktop = self.oorunner.connect() inputUrl = uno.systemPathToFileUrl(os.path.abspath(inputFile)) outputUrl = uno.systemPathToFileUrl(os.path.abspath(outputFile)) try: document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, ooutils.oo_properties(Hidden=False)) except IllegalArgumentException, e: raise IOError( "Failed to open '%s': %s" % (inputFile, e.Message) )
def convertOffice(inputFileUrl, outputFileUrl): nRes = ErrorTypes["NoError"] try: desktop = initOffice() alert("office desktop created") inputFileUrl = uno.systemPathToFileUrl(abspath(inputFileUrl)) alert("from " + inputFileUrl) outputFileUrl = uno.systemPathToFileUrl(abspath(outputFileUrl)) alert("to " + outputFileUrl) loadProperties = { "Hidden": True } inputExt = getFileExt(inputFileUrl) if importFilterMap.get(inputExt): loadProperties.update(importFilterMap[inputExt]) alert("document loading") document = desktop.loadComponentFromURL(inputFileUrl, "_blank", 0, toProperties(loadProperties)) alert("document loaded") try: document.refresh() except AttributeError: pass family = detectFamily(document) overridePageStyleProperties(document, family) outputExt = getFileExt(outputFileUrl) storeProperties = getStoreProperties(document, outputExt) alert("document storing") try: document.storeToURL(outputFileUrl, toProperties(storeProperties)) alert("document stored") finally: document.close(True) except: alert("Error convert", True) nRes = ErrorTypes["ConvertLibreOffice"] return nRes
def oeffne_text(self, pfad_translation): if self.mb.debug: log(inspect.stack) prop = uno.createUnoStruct("com.sun.star.beans.PropertyValue") prop.Name = 'Hidden' prop.Value = True url = uno.systemPathToFileUrl(pfad_translation) self.ooo = self.mb.doc.CurrentController.Frame.loadComponentFromURL( url, '_blank', 0, (prop, )) return self.ooo.Text
def processfile(sourcefile, footerfile, resultfile): print "Converting '%(s)s' with footer '%(f)s' , to resulting PDF: '%(r)s'" % {"s":sourcefile , "f":footerfile , "r":resultfile} port=2002 localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext ) try: context = resolver.resolve( "uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext" % port ) except NoConnectException: raise DocumentConversionException, "failed to connect to OpenOffice.org on port %s" % port desktop = context.ServiceManager.createInstanceWithContext( "com.sun.star.frame.Desktop", context ) sourceurl = uno.systemPathToFileUrl(os.path.abspath(sourcefile)) footerurl = uno.systemPathToFileUrl(os.path.abspath(footerfile)) targeturl = uno.systemPathToFileUrl(os.path.abspath(resultfile)) docsource = desktop.loadComponentFromURL(sourceurl, "_blank", 0, _toProperties({ "Hidden": True, "FilterName": "<All formats>" })) docsource.Text.getEnd().insertDocumentFromURL(footerurl, _toProperties({ "Hidden": True })) ##docsource.Text.getEnd().setString("\nThis is the end") ##docsource.Text.getEnd().setString("\nFinish") docsource.storeToURL(targeturl, _toProperties({ "FilterName": "writer_pdf_Export" })) docsource.close(True) context.ServiceManager
def load_component(component_path, component_name): import os import os.path import uno from unokit.services import css loader = css.loader.Python() if loader: component_path = os.path.abspath(component_path) component_url = uno.systemPathToFileUrl(component_path) return loader.activate(component_name, '', component_url, None)
def save_as(document, path): """[document].save_as(['path'])""" url = systemPathToFileUrl(path) # Set file to overwrite property_value = PropertyValue() property_value.Name = 'Overwrite' property_value.Value = 'overwrite' properties = (property_value,) # Save to file document.storeAsURL(url, properties) return True
def convertFile(self, outputFormat, inputFilename): if self.desktop: tOldFileName = os.path.splitext(inputFilename) outputFilename = "%s.%s" % (tOldFileName[0], outputFormat) inputFormat = tOldFileName[1].replace(".","") inputUrl = uno.systemPathToFileUrl(os.path.abspath(inputFilename)) outputUrl = uno.systemPathToFileUrl(os.path.abspath(outputFilename)) if inputFormat in LIBREOFFICE_IMPORT_TYPES: inputProperties = { "Hidden": True } inputProperties.update(LIBREOFFICE_IMPORT_TYPES[inputFormat]) doc = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self.propertyTuple(inputProperties)) try: doc.refresh() except: pass docFamily = self.getDocumentFamily(doc) if docFamily: try: outputProperties = LIBREOFFICE_EXPORT_TYPES[outputFormat][docFamily] doc.storeToURL(outputUrl, self.propertyTuple(outputProperties)) doc.close(True) return True except Exception as e: self.__lastErrorMessage = str(e) self.terminateProcess() return False
def odt_to_pdf(ifile, ofile): # Begin Main ''' Here is the sequence of things the lines do: 1. Get the uno component context from the PyUNO runtime 2. Create the UnoUrlResolver 3. Get the central desktop object 4. Declare the ServiceManager 5. Get the central desktop object 6. Access the current writer document 7. Access the document's text property 8. Create a cursor 9. Insert the text into the document ''' localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext) ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext") # Теперь можно модифицировать содержимое smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx) # Загружаем существующий документ doc_java = desktop.loadComponentFromURL(uno.systemPathToFileUrl(ifile) ,"_blank", 0, ()) # Сохряняем документ ctx.ServiceManager # зачем интересно этот вызов # Получаем текущий документ? doc = desktop.getCurrentComponent() # to pdf doc.storeToURL(uno.systemPathToFileUrl(ofile), uinit.getPdfProps()) doc_java.dispose() return 0, ''
def saveAs( self, filename ): """Save the open office document to a new file, and possibly filetype. The type of document is parsed out of the file extension of the filename given.""" self.filename = os.path.abspath( filename ) filename = uno.systemPathToFileUrl( self.filename ) #filterlist: http://wiki.services.openoffice.org/wiki/Framework/Article/Filter/FilterList_OOo_3_0 exportFilter = self._getExportFilter( filename ) props = exportFilter, try: #if the filetype is a pdf this will crap-out self.oodocument.storeAsURL( filename, props ) except: self.oodocument.storeToURL( filename, props ) return self.getFilename()
def save_as_pdf(document, path): """[document].save_as_pdf(['path'])""" url = systemPathToFileUrl(path) # Set file type to pdf property_value = PropertyValue() property_value.Name = 'FilterName' property_value.Value = 'writer_pdf_Export' properties = (property_value,) # Store file document.storeToURL(url, properties) return True
def test_insertDocument(self): ood = WriterDocument() ood.open("%s/docs/find_replace.odt" % self.path) cursor = ood.oodocument.Text.createTextCursor() replace = ood.oodocument.createReplaceDescriptor() replace.setSearchString("search") replace.setReplaceString("replace") ood.oodocument.replaceAll(replace) ood.oodocument.Text.insertString(cursor, "inserted", 0) properties = [] properties = tuple(properties) cursor.insertDocumentFromURL(uno.systemPathToFileUrl("%s/docs/insert_doc.odt" % self.path), properties) ood.saveAs("%s/docs/inserted_doc.pdf" % self.path) ood.close()
def openofficeconv(importfile): exportfile = importfile.split('.')[0] + '.html' importfileurl = uno.systemPathToFileUrl(abspath(importfile)) exportfileurl = uno.systemPathToFileUrl(abspath(exportfile)) filter = PropertyValue() filter.Name = "Hidden" filter.Value = True document = desktop.loadComponentFromURL(importfileurl,'_blank',0,tuple([filter])) filter = PropertyValue() filter.Name = "FilterName" filter.Value = "XHTML Impress File" document.storeToURL(exportfileurl, tuple([filter])) return exportfile
def replace_text_with_file_contents(self, document, placeholder_text, file_name): """ Inserts the given file into the current document. The file contents will replace the placeholder text. """ import uno file_url = uno.systemPathToFileUrl(abspath(file_name)) search = document.createSearchDescriptor() search.SearchString = placeholder_text found = document.findFirst( search ) while found: try: found.insertDocumentFromURL(file_url, ()) except Exception, ex: raise OOHelperException(_("Error inserting file %s on the OpenOffice document: %s") % (file_name, ex)) found = document.findNext(found, search)