Example #1
0
 /// <summary>
 /// Save currently loaded document of given frame.
 /// </summary>
 /// <param name="xDocument">document for saving changes</param>
 public static void SaveDocument(XComponent xDocument)
 {
     try
     {
         // Check for supported model functionality.
         // Normally the application documents (text, spreadsheet ...) do so
         // but some other ones (e.g. db components) doesn't do that.
         // They can't be save then.
         var xModel = (XModel)xDocument;
         if (xModel != null)
         {
             // Check for modifications => break save process if there is nothing to do.
             XModifiable xModified = (XModifiable)xModel;
             if (xModified.isModified() == true)
             {
                 XStorable xStore = (XStorable)xModel;
                 xStore.store();
             }
         }
     }
     catch (unoidl.com.sun.star.io.IOException exIo)
     {
         // Can be thrown by "store()" call.
         // But there is nothing we can do then.
         System.Diagnostics.Debug.WriteLine(exIo);
     }
     catch (RuntimeException exUno)
     {
         // Any UNO method of this scope can throw this exception.
         // But there is nothing we can do then.
         System.Diagnostics.Debug.WriteLine(exUno);
     }
 }
Example #2
0
        private Workbook(Uri uri)
        {
            if (uri.Scheme.ToLower() == "file")
            {
                if (!File.Exists(uri.LocalPath))
                {
                    throw new FileNotFoundException(uri.LocalPath);
                }
            }

            var aLoader = OfficeServiceManager.loader;

            Peer = (XSpreadsheetDocument)aLoader.loadComponentFromURL(
                uri.AbsoluteUri, "_blank", 0,
                new[] {
                new PropertyValue()
                {
                    Name  = "Hidden",
                    Value = new uno.Any(true)
                },
                new PropertyValue()
                {
                    Name  = "MacroExecutionMode",
                    Value = new uno.Any(MacroExecMode.FROM_LIST_NO_WARN)
                }
            }
                );

            this.storePeer       = (XStorable)Peer;
            this.closePeer       = (XCloseable)Peer;
            this.propSetPeer     = (XPropertySet)Peer;
            this.FormatsSupplier = (XNumberFormatsSupplier)Peer;
        }
Example #3
0
 private void storeDocument(XComponent document, String outputUrl, IDictionary storeProperties)
 {
     try
     {
         XStorable storable = (XStorable)document;
         storable.storeToURL(outputUrl, ToPropertyValues(storeProperties));
     }
     finally
     {
         XCloseable closeable = (XCloseable)document;
         if (closeable != null)
         {
             try
             {
                 closeable.close(true);
             }
             catch (CloseVetoException closeVetoException)
             {
                 Logger.Warn("document.close() vetoed:" + closeVetoException.Message);
             }
         }
         else
         {
             document.dispose();
         }
     }
 }
    private static void ConvertToPDF(string serverHost, int serverPort, Uri inputFile, Uri outputFile)
    {
        // FIX: Workaround for a known bug: XUnoUrlResolver forgets to call WSAStartup. We can use dummy Socket for that:
        using (var dummySocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP))
        {
            // First, initialize local service manager (IoC container of some kind):
            XComponentContext      componentContext    = Bootstrap.bootstrap();
            XMultiComponentFactory localServiceManager = componentContext.getServiceManager();
            XUnoUrlResolver        urlResolver         = (XUnoUrlResolver)localServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", componentContext);

            // Connect to LibreOffice server
            // URL format explained here: https://wiki.openoffice.org/wiki/Documentation/DevGuide/ProUNO/Starting_OpenOffice.org_in_Listening_Mode
            string connectionString = string.Format("uno:socket,host={0},port={1};urp;StarOffice.ComponentContext", serverHost, serverPort);
            object initialObject    = urlResolver.resolve(connectionString);

            // Retrieve remote service manager:
            XComponentContext      remoteContext          = (XComponentContext)initialObject;
            XMultiComponentFactory remoteComponentFactory = remoteContext.getServiceManager();

            // Request our own instance of LibreOffice Writer from the server:
            object           oDesktop = remoteComponentFactory.createInstanceWithContext("com.sun.star.frame.Desktop", remoteContext);
            XComponentLoader xCLoader = (XComponentLoader)oDesktop;

            var loaderArgs = new PropertyValue[1];
            loaderArgs[0]       = new PropertyValue();
            loaderArgs[0].Name  = "Hidden"; // No GUI
            loaderArgs[0].Value = new Any(true);

            string inputFileUrl = inputFile.AbsoluteUri;

            // WARNING: LibreOffice .NET API uses .NET Remoting and does NOT throw clean and actionable errors,
            //          so, if server crashes or input file is locked or whatever, you will get nulls after casting.
            //          For example, `(XStorable)xCLoader` cast may produce null.
            //          This is counter-intuitive, I know; be more careful in production-grade code and check for nulls after every cast.

            XStorable xStorable = (XStorable)xCLoader.loadComponentFromURL(inputFileUrl, "_blank", 0, loaderArgs);

            var writerArgs = new PropertyValue[2];
            writerArgs[0]       = new PropertyValue();
            writerArgs[0].Name  = "Overwrite"; // Overwrite outputFile if it already exists
            writerArgs[0].Value = new Any(true);
            writerArgs[1]       = new PropertyValue();
            writerArgs[1].Name  = "FilterName";
            writerArgs[1].Value = new Any("writer_pdf_Export");  // Important! This filter is doing all PDF stuff.

            string outputFileUrl = outputFile.AbsoluteUri;

            xStorable.storeToURL(outputFileUrl, writerArgs);

            XCloseable xCloseable = (XCloseable)xStorable;
            if (xCloseable != null)
            {
                xCloseable.close(false);
            }
        }
    }
Example #5
0
        //ファイルを上書き保存して閉じる
        public bool SaveFile()
        {
            // Calcファイルを保存
            xstorable           = (XStorable)doc;
            storeProps          = new PropertyValue[1];
            storeProps[0]       = new PropertyValue();
            storeProps[0].Name  = "Overwrite";    // 上書き
            storeProps[0].Value = new uno.Any(true);

            try
            {
                xstorable.storeAsURL(uriCalcFile.ToString(), storeProps);    // 保存
                CloseFile();
                return(true);
            }
            catch (unoidl.com.sun.star.uno.Exception)
            {
                return(false);
            }
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="importOptions"></param>
        /// <param name="outputStream"></param>
        /// <param name="exportOptions"></param>
        /// <remarks></remarks>
        private void LoadAndExport(Stream inputStream, IDictionary importOptions, Stream outputStream, IDictionary exportOptions)
        {
            XComponentLoader desktop = OpenOfficeConnection.Desktop;


            IDictionary loadProperties = new Hashtable();

            SupportClass.MapSupport.PutAll(loadProperties, DefaultLoadProperties);
            SupportClass.MapSupport.PutAll(loadProperties, importOptions);
            // doesn't work using InputStreamToXInputStreamAdapter; probably because it's not XSeekable
            //property("InputStream", new InputStreamToXInputStreamAdapter(inputStream))
            loadProperties["InputStream"] = new Any(typeof(XInputStream), new XInputStreamWrapper(inputStream));

            XComponent document = desktop.loadComponentFromURL("private:stream", "_blank", 0, ToPropertyValues(loadProperties));

            if (document == null)
            {
                throw new OpenOfficeException("conversion failed: input document is null after loading");
            }

            RefreshDocument(document);


            IDictionary storeProperties = new Hashtable();

            SupportClass.MapSupport.PutAll(storeProperties, exportOptions);
            storeProperties["OutputStream"] = new Any(typeof(XOutputStream), new XOutputStreamWrapper(outputStream));

            try
            {
                XStorable storable = (XStorable)document;
                storable.storeToURL("private:stream", ToPropertyValues(storeProperties));
            }
            finally
            {
                document.dispose();
            }
        }
Example #7
0
        /// <summary>
        /// It try to export given document in HTML format.
        /// Current document will be converted to HTML and moved to new place on disk.
        /// A "new" file will be created by given URL (may be overwritten
        /// if it already exist). Right filter will be used automatically if factory of
        /// this document support it. If no valid filter can be found for export,
        /// nothing will be done here.
        /// </summary>
        /// <param name="xDocument">document which should be exported</param>
        /// <param name="sUrl">target URL for converted document</param>
        public static void SaveAsHtml(XComponent xDocument, String sUrl)
        {
            try
            {
                // First detect factory of this document.
                // Ask for the supported service name of this document.
                // If information is available it can be used to find out which
                // filter exist for HTML export. Normally this filter should be searched
                // inside the filter configuration but this little demo doesn't do so.
                // (see service com.sun.star.document.FilterFactory for further
                // informations too)
                // Well known filter names are used directly. They must exist in current
                // office installation. Otherwise this code will fail. But to prevent
                // this code against missing filters it check for existing state of it.
                XServiceInfo xInfo = (XServiceInfo)xDocument;

                if (xInfo != null)
                {
                    // Find out possible filter name.
                    String sFilter = null;
                    if (xInfo.supportsService(OO.Services.DOCUMENT_TEXT))
                    {
                        sFilter = "HTML (StarWriter)";
                    }
                    else
                    if (xInfo.supportsService(OO.Services.DOCUMENT_WEB))
                    {
                        sFilter = "HTML";
                    }
                    else
                    if (xInfo.supportsService(OO.Services.DOCUMENT_SPREADSHEET))
                    {
                        sFilter = "HTML (StarCalc)";
                    }

                    // Check for existing state of this filter.
                    if (sFilter != null)
                    {
                        XComponentContext xCtx = OO.GetContext();

                        var xFilterContainer = (XNameAccess)xCtx.getServiceManager().createInstanceWithContext(
                            OO.Services.DOCUMENT_FILTER_FACTORY, xCtx);

                        if (xFilterContainer.hasByName(sFilter) == false)
                        {
                            sFilter = null;
                        }
                    }

                    // Use this filter for export.
                    if (sFilter != null)
                    {
                        // Export can be forced by saving the document and using a
                        // special filter name which can write needed format. Build
                        // necessary argument list now.
                        // Use special flag "Overwrite" too, to prevent operation
                        // against possible exceptions, if file already exist.
                        var lProperties = new PropertyValue[2];
                        lProperties[0] = new PropertyValue {
                            Name = "FilterName", Value = Any.Get(sFilter)
                        };
                        lProperties[1] = new PropertyValue {
                            Name = "Overwrite", Value = Any.Get(true)
                        };

                        XStorable xStore = (XStorable)xDocument;

                        xStore.storeAsURL(sUrl, lProperties);
                    }
                }
            }
            catch (unoidl.com.sun.star.io.IOException exIo)
            {
                // Can be thrown by "store()" call.
                // Do nothing then. Saving failed - that's it.
                System.Diagnostics.Debug.WriteLine(exIo);
            }
            catch (RuntimeException exRuntime)
            {
                // Can be thrown by any uno call.
                // Do nothing here. Saving failed - that's it.
                System.Diagnostics.Debug.WriteLine(exRuntime);
            }
            catch (unoidl.com.sun.star.uno.Exception exUno)
            {
                // Can be thrown by "createInstance()" call of service manager.
                // Do nothing here. Saving failed - that's it.
                System.Diagnostics.Debug.WriteLine(exUno);
            }
        }
Example #8
0
 public static void SaveFile(XStorable XStorable)
 {
     XStorable.store();
 }