private void SaveDocument(XComponent xComponent, string sourceFile, string destinationFile)
 {
     var propertyValues = new PropertyValue[2];
     // Setting the flag for overwriting
     propertyValues[1] = new PropertyValue { Name = "Overwrite", Value = new Any(true) };
     //// Setting the filter name
     propertyValues[0] = new PropertyValue
     {
         Name = "FilterName",
         Value = new Any(ConvertExtensionToFilterType(Path.GetExtension(sourceFile)))
     };
     ((XStorable)xComponent).storeToURL(destinationFile, propertyValues);
 }
Ejemplo n.º 2
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();
         }
     }
 }
Ejemplo n.º 3
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);
     }
 }
Ejemplo n.º 4
0
        public override ListViewItem SetupListViewItem(ListViewItem item, XComponent component)
        {
            XProp prop = new XProp(ref X, null, Vector3.Zero, Vector3.Zero, Matrix.Identity, Vector3.One);

            prop.NoCull = true;
            return(base.SetupListViewItem(item, prop));
        }
Ejemplo n.º 5
0
        public void CreateNewDocumentAndDoAPrintOut()
        {
            string fileToPrint = AARunMeFirstAndOnce.outPutFolder + "fileToPrint.odt";

            //Create a new text document
            TextDocument document = new TextDocument();

            document.New();
            //Create a standard paragraph using the ParagraphBuilder
            Paragraph paragraph = ParagraphBuilder.CreateStandardTextParagraph(document);

            //Add some simple text
            paragraph.TextContent.Add(new SimpleText(document, "Some simple text!"));
            //Add the paragraph to the document
            document.Content.Add(paragraph);
            //Save empty
            document.SaveTo(fileToPrint);

            //Now print the new document via the OpenOfficeLib
            //Get the Component Context
            XComponentContext xComponentContext = Connector.GetComponentContext();
            //Get a MultiServiceFactory
            XMultiServiceFactory xMultiServiceFactory = Connector.GetMultiServiceFactory(xComponentContext);
            //Get a Dektop instance
            XDesktop xDesktop = Connector.GetDesktop(xMultiServiceFactory);

            //Convert a windows path to an OpenOffice one
            fileToPrint = Component.PathConverter(fileToPrint);
            //Load the document you want to print
            XComponent xComponent = Component.LoadDocument(
                (XComponentLoader)xDesktop, fileToPrint, "_blank");

            //Print the XComponent
            Printer.Print(xComponent);
        }
Ejemplo n.º 6
0
        public static void ConvertToPdf(string inputFile, string outputFile)
        {
            if (ConvertExtensionToFilterType(Path.GetExtension(inputFile)) == null)
            {
                throw new InvalidProgramException("Unknown file type for OpenOffice. File = " + inputFile);
            }

            //StartOpenOffice();

            //Get a ComponentContext
            var xLocalContext = Bootstrap.bootstrap();
            //Get MultiServiceFactory
            XMultiServiceFactory xRemoteFactory = (XMultiServiceFactory)xLocalContext.getServiceManager();
            //Get a CompontLoader
            XComponentLoader aLoader = (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");
            //Load the sourcefile

            XComponent xComponent = null;

            try
            {
                xComponent = initDocument(aLoader, PathConverter(inputFile), "_blank");
                //Wait for loading
                while (xComponent == null)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                // save/export the document
                saveDocument(xComponent, inputFile, PathConverter(outputFile));
            }
            catch { throw; }
            finally { xComponent.dispose(); }
        }
Ejemplo n.º 7
0
        public override ListViewItem SetupListViewItem(ListViewItem item, XComponent component)
        {
            XEnvironmentParameters paramaters = new XEnvironmentParameters(X);

            paramaters.Load(X.Content);
            return(base.SetupListViewItem(item, paramaters));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 初始化一个文档
        /// </summary>
        /// <returns>该文档的XSpreadsheetDocument接口</returns>
        private unoidl.com.sun.star.sheet.XSpreadsheetDocument initDocument(string filepath, bool IsHidden)
        {
            XComponentLoader aLoader = (XComponentLoader)
                                       mxMSFactory.createInstance("com.sun.star.frame.Desktop");
            XComponent xComponent = null;

            unoidl.com.sun.star.beans.PropertyValue[] myArgs = new unoidl.com.sun.star.beans.PropertyValue[1];
            myArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            myArgs[0].Name  = "Hidden";
            myArgs[0].Value = new uno.Any(IsHidden);
            if (filepath == "")
            {
                xComponent = aLoader.loadComponentFromURL(
                    "private:factory/scalc", "_blank", 0,
                    myArgs);
            }
            else
            {
                xComponent = aLoader.loadComponentFromURL(
                    this.PathConverter(filepath), "_blank", 0,
                    myArgs);
            }

            return((unoidl.com.sun.star.sheet.XSpreadsheetDocument)xComponent);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     Exports the loaded document to PDF format
        /// </summary>
        /// <param name="component"></param>
        /// <param name="inputFile"></param>
        /// <param name="outputFile"></param>
        private void ExportToPdf(XComponent component, string inputFile, string outputFile)
        {
            Logger.WriteToLog($"Exporting document to PDF file '{outputFile}'");

            var propertyValues = new PropertyValue[3];
            var filterData     = new PropertyValue[5];

            filterData[0] = new PropertyValue
            {
                Name  = "UseLosslessCompression",
                Value = new Any(false)
            };

            filterData[1] = new PropertyValue
            {
                Name  = "Quality",
                Value = new Any(90)
            };

            filterData[2] = new PropertyValue
            {
                Name  = "ReduceImageResolution",
                Value = new Any(true)
            };

            filterData[3] = new PropertyValue
            {
                Name  = "MaxImageResolution",
                Value = new Any(300)
            };

            filterData[4] = new PropertyValue
            {
                Name  = "ExportBookmarks",
                Value = new Any(false)
            };

            // Setting the filter name
            propertyValues[0] = new PropertyValue
            {
                Name  = "FilterName",
                Value = new Any(GetFilterType(inputFile))
            };

            // Setting the flag for overwriting
            propertyValues[1] = new PropertyValue {
                Name = "Overwrite", Value = new Any(true)
            };

            var polymorphicType = PolymorphicType.GetType(typeof(PropertyValue[]), "unoidl.com.sun.star.beans.PropertyValue[]");

            propertyValues[2] = new PropertyValue {
                Name = "FilterData", Value = new Any(polymorphicType, filterData)
            };

            // ReSharper disable once SuspiciousTypeConversion.Global
            ((XStorable)component).storeToURL(ConvertToUrl(outputFile), propertyValues);

            Logger.WriteToLog("Document exported to PDF");
        }
Ejemplo n.º 10
0
        public override ListViewItem SetupListViewItem(ListViewItem item, XComponent component)
        {
            XWater water = new XWater(ref X);

            water.Load(X.Content);
            return(base.SetupListViewItem(item, water));
        }
Ejemplo n.º 11
0
        public void OpenODT(string inputFile)
        {
            StartOpenOffice();

            //Get a ComponentContext
            var xLocalContext =
                Bootstrap.bootstrap();
            //Get MultiServiceFactory
            var xRemoteFactory =
                (XMultiServiceFactory)
                xLocalContext.getServiceManager();
            //Get a CompontLoader
            var aLoader =
                (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");
            //Load the sourcefile

            XComponent xComponent = null;

            xComponent = InitDocument(aLoader,
                                      PathConverter(inputFile), "_blank");
            //Wait for loading
            while (xComponent == null)
            {
                Thread.Sleep(1000);
            }
            ODTText = ((XTextDocument)xComponent).getText().getString();
            if (xComponent != null)
            {
                xComponent.dispose();
            }
        }
Ejemplo n.º 12
0
        public virtual void Connect()
        {
            Logger.Debug("connecting");
            try
            {
                EnvUtils.InitUno();
                SocketUtils.Connect();
                //var sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                XComponentContext localContext = Bootstrap.bootstrap();
                //XComponentContext localContext = Bootstrap.defaultBootstrap_InitialComponentContext();
                XMultiComponentFactory localServiceManager = localContext.getServiceManager();
                XConnector             connector           = (XConnector)localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector", localContext);
                XConnection            connection          = connector.connect(_connectionString);
                XBridgeFactory         bridgeFactory       = (XBridgeFactory)localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext);
                _bridge          = bridgeFactory.createBridge("", "urp", connection, null);
                _bridgeComponent = (XComponent)_bridge;
                _bridgeComponent.addEventListener(this);
                _serviceManager = (XMultiComponentFactory)_bridge.getInstance("StarOffice.ServiceManager");
                XPropertySet properties = (XPropertySet)_serviceManager;
                // Get the default context from the office server.
                var oDefaultContext = properties.getPropertyValue("DefaultContext");

                _componentContext = (XComponentContext)oDefaultContext.Value;
                _connected        = true;
                Logger.Info("connected");
            }
            catch (NoConnectException connectException)
            {
                throw new OpenOfficeException("connection failed: " + _connectionString + ": " + connectException.Message);
            }
            catch (Exception exception)
            {
                throw new OpenOfficeException("connection failed: " + _connectionString, exception);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Try to close the document without any saving of modifications.
        /// We can try it only! Controller and/or model of this document
        /// can disagree with that. But mostly they doesn't do so.
        /// </summary>
        /// <param name="xDocument">document which should be clcosed</param>
        public static void CloseDocument(XComponent xDocument)
        {
            try
            {
                // Check supported functionality of the document (model or controller).
                XModel xModel = (XModel)xDocument;

                if (xModel != null)
                {
                    // It's a full featured office document.
                    // Reset the modify state of it and close it.
                    // Note: Model can disagree by throwing a veto exception.
                    XModifiable xModify = (XModifiable)xModel;

                    xModify.setModified(false);
                    xDocument.dispose();
                }
                else
                {
                    // It's a document which supports a controller .. or may by a pure
                    // window only. If it's at least a controller - we can try to
                    // suspend him. But - he can disagree with that!
                    XController xController = (XController)xDocument;

                    if (xController != null)
                    {
                        if (xController.suspend(true))
                        {
                            // Note: Don't dispose the controller - destroy the frame
                            // to make it right!
                            XFrame xFrame = xController.getFrame();
                            xFrame.dispose();
                        }
                    }
                }
            }
            catch (PropertyVetoException exVeto)
            {
                // Can be thrown by "setModified()" call on model.
                // He disagree with our request.
                // But there is nothing to do then. Following "dispose()" call wasn't
                // never called (because we catch it before). Closing failed -that's it.
                System.Diagnostics.Debug.WriteLine(exVeto);
            }
            catch (DisposedException exDisposed)
            {
                // If an UNO object was already disposed before - he throw this special
                // runtime exception. Of course every UNO call must be look for that -
                // but it's a question of error handling.
                // For demonstration this exception is handled here.
                System.Diagnostics.Debug.WriteLine(exDisposed);
            }
            catch (RuntimeException exRuntime)
            {
                // Every uno call can throw that.
                // Do nothing - closing failed - that's it.
                System.Diagnostics.Debug.WriteLine(exRuntime);
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 /// A global function that prevents showing component's validation error tooltip,
 /// if there are no errors or if the component is in the grid, which shows it's own error.
 /// </summary>
 /// <param name="comp">Component with the error.</param>
 /// <param name="args">Tooltip arguments.</param>
 public static void ShowTooltipError(XComponent comp, TooltipEventArgs args)
 {
     // don't show error tooltip if there are no errors or when editing a grid, which shows its own error
     if (string.IsNullOrEmpty(comp.ErrorsText) || comp.Row != null)
     {
         args.Cancel = true;
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        ///     Closes the document and frees any used resources
        /// </summary>
        private void CloseDocument(XComponent component)
        {
            Logger.WriteToLog("Closing document");
            var closeable = (XCloseable)component;

            closeable?.close(false);
            Logger.WriteToLog("Document closed");
        }
Ejemplo n.º 16
0
		/// <summary>
		/// Prints the specified XComponent that could be any loaded
		/// OpenOffice document e.g text document, spreadsheet document, ..
		/// </summary>
		/// <param name="xComponent">The x component.</param>
		public static void Print(XComponent xComponent)
		{
			if (xComponent is unoidl.com.sun.star.view.XPrintable)
				((unoidl.com.sun.star.view.XPrintable)xComponent).print(
					new PropertyValue[] {}); 
			else
				throw new NotSupportedException("The given XComponent doesn't implement the XPrintable interface.");
		}
Ejemplo n.º 17
0
        public override ListViewItem SetupListViewItem(ListViewItem item, XComponent component)
        {
            XTree actor = new XTree(ref X, null, Vector3.Zero, Vector3.One);

            actor.NoCull = true;

            return(base.SetupListViewItem(item, actor));
        }
Ejemplo n.º 18
0
        public override ListViewItem SetupListViewItem(ListViewItem item, XComponent component)
        {
            XAnimatedActor actor = new XAnimatedActor(ref X, null, Vector3.Zero, Vector3.Zero, 1);

            actor.NoCull    = true;
            actor.Immovable = true;

            return(base.SetupListViewItem(item, actor));
        }
Ejemplo n.º 19
0
        protected internal virtual void RefreshDocument(XComponent document)
        {
            XRefreshable refreshable = (XRefreshable)document;

            if (refreshable != null)
            {
                refreshable.refresh();
            }
        }
Ejemplo n.º 20
0
        protected XDrawPagesSupplier UseDraw()
        {
            try
            {
                //create new draw document and insert rectangle shape
                XComponent         xDrawComponent     = NewDocComponent("sdraw");
                XDrawPagesSupplier xDrawPagesSupplier = xDrawComponent as XDrawPagesSupplier;

                Object       drawPages         = xDrawPagesSupplier.getDrawPages();
                XIndexAccess xIndexedDrawPages = drawPages as XIndexAccess;

                Object drawPage = xIndexedDrawPages.getByIndex(0).Value;

                System.Diagnostics.Debug.WriteLine(xIndexedDrawPages.getCount());

                if (drawPage is XDrawPage)
                {
                    XDrawPage xDrawPage = (XDrawPage)drawPage;

                    if (xDrawPage is XComponent)
                    {
                        (xDrawPage as XComponent).addEventListener(new TestOOoEventListerner());
                    }

                    // get internal service factory of the document
                    XMultiServiceFactory xDrawFactory = xDrawComponent as XMultiServiceFactory;

                    Object drawShape = xDrawFactory.createInstance(
                        "com.sun.star.drawing.RectangleShape");
                    XShape xDrawShape = drawShape as XShape;
                    xDrawShape.setSize(new Size(10000, 20000));
                    xDrawShape.setPosition(new Point(5000, 5000));
                    xDrawPage.add(xDrawShape);

                    // XText xShapeText = (XText)drawShape // COMMENTED BY CODEIT.RIGHT;
                    XPropertySet xShapeProps = (XPropertySet)drawShape;

                    // wrap text inside shape
                    xShapeProps.setPropertyValue("TextContourFrame", new uno.Any(true));
                    return(xDrawPagesSupplier);
                }
                else
                {
                    //TODO: handle if no drwapage was found
                    System.Diagnostics.Debug.WriteLine("no XDrawPage found");
                    System.Diagnostics.Debug.WriteLine(drawPage);
                }
            }
            catch (unoidl.com.sun.star.lang.DisposedException e)
            { //works from Patch 1
                MXContext = null;
                throw e;
            }

            return(null);
        }
        public string TestPDF()
        {
            var    statuscode = "";
            string inputFile  = @"C:\ALISS_ProcessFile\GLASS\test.txt";
            string outputFile = @"C:\ALISS_ProcessFile\GLASS\test.pdf";

            if (ConvertExtensionToFilterType(Path.GetExtension(inputFile)) == null)
            {
                throw new InvalidProgramException("Unknown file type for OpenOffice. File = " + inputFile);
            }

            StartOpenOffice();

            //Get a ComponentContext
            var xLocalContext =
                Bootstrap.bootstrap();
            //Get MultiServiceFactory
            var xRemoteFactory =
                (XMultiServiceFactory)
                xLocalContext.getServiceManager();
            //Get a CompontLoader
            var aLoader =
                (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");
            //Load the sourcefile

            XComponent xComponent = null;

            try
            {
                xComponent = InitDocument(aLoader,
                                          PathConverter(inputFile), "_blank");
                //Wait for loading
                while (xComponent == null)
                {
                    Thread.Sleep(1000);
                }

                // save/export the document
                SaveDocument(xComponent, inputFile, PathConverter(outputFile));
                statuscode = "OK";
            }
            catch
            {
                statuscode = "Error";
            }
            finally
            {
                if (xComponent != null)
                {
                    xComponent.dispose();
                }
            }

            return("Gen PDF status : " + statuscode);
        }
Ejemplo n.º 22
0
    /** Creates an empty spreadsheet document.
     *  @return  The XSpreadsheetDocument interface of the document. */
    private unoidl.com.sun.star.sheet.XSpreadsheetDocument initDocument()
    {
        XComponentLoader aLoader = (XComponentLoader)
                                   mxMSFactory.createInstance("com.sun.star.frame.Desktop");

        XComponent xComponent = aLoader.loadComponentFromURL(
            "private:factory/scalc", "_blank", 0,
            new unoidl.com.sun.star.beans.PropertyValue[0]);

        return((unoidl.com.sun.star.sheet.XSpreadsheetDocument)xComponent);
    }
        private void searchForDocs()
        {
            while (serach)
            {
                try
                {
                    if (XDesktop != null)
                    {
                        XEnumerationAccess xEnumerationAccess = XDesktop.getComponents();
                        XEnumeration       enummeraration     = xEnumerationAccess.createEnumeration();

                        var _uids = DesktopDocumentComponents.Keys;

                        while (enummeraration.hasMoreElements())
                        {
                            Any        anyelemet = enummeraration.nextElement();
                            XComponent element   = anyelemet.Value as XComponent;
                            if (element != null)
                            {
                                //FIXME: for debugging
                                //System.Diagnostics.Debug.WriteLine("Window from Desktop found _________________");
                                //Debug.GetAllInterfacesOfObject(element);
                                //System.Diagnostics.Debug.WriteLine("\tProperties _________________");
                                //Debug.GetAllProperties(element);
                                XPropertySet ps = element as XPropertySet;
                                if (ps != null)
                                {
                                    var uid = OoUtils.GetStringProperty(ps, "RuntimeUID");
                                    if (uid != null && !uid.Equals(""))
                                    {
                                        if (!DesktopDocumentComponents.ContainsKey(uid))
                                        {
                                            //FIXME: for fixing
                                            Console.WriteLine("Found new Desktop child with uid:" + uid);
                                            DesktopDocumentComponents.Add(uid, element);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (DisposedException dex) {
                    this.Dispose();
                    throw dex;
                }
                catch (System.Exception) { }


                //Console.WriteLine("\t\tSearch for Docs");
                Thread.Sleep(WAIT_TIME);
            }
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Prints the specified XComponent that could be any loaded
 /// OpenOffice document e.g text document, spreadsheet document, ..
 /// </summary>
 /// <param name="xComponent">The x component.</param>
 public static void Print(XComponent xComponent)
 {
     if (xComponent is unoidl.com.sun.star.view.XPrintable)
     {
         ((unoidl.com.sun.star.view.XPrintable)xComponent).print(
             new PropertyValue[] {});
     }
     else
     {
         throw new NotSupportedException("The given XComponent doesn't implement the XPrintable interface.");
     }
 }
Ejemplo n.º 25
0
 public override void AssignChildComponents(XComponent parent, ref List <uint> children)
 {
     foreach (uint childID in children)
     {
         XComponent child = X.Tools.GetXComponentByID(childID);
         if (child.GetType() == typeof(XModel))
         {
             ((XProp)parent).model_editor = (XModel)child;
         }
     }
     //base.AssignChildComponents(parent, ref children);
 }
Ejemplo n.º 26
0
 public override void AssignChildComponents(XComponent parent, ref List <uint> children)
 {
     foreach (uint childID in children)
     {
         XComponent child = X.Tools.GetXComponentByID(childID);
         if (child.GetType() == typeof(XEnvironmentParameters))
         {
             ((XHeightMap)parent).Params = (XEnvironmentParameters)child;
             parent.Load(X.Content);
         }
     }
 }
Ejemplo n.º 27
0
 public override void AssignChildComponents(XComponent parent, ref List <uint> children)
 {
     if (children.Count == 1)
     {
         XActor xparent = (XActor)parent;
         XModel child   = (XModel)X.Tools.GetXComponentByID(children[0]);
         if (child.GetType() == typeof(XModel))
         {
             xparent.model_editor = child;
             xparent.RebuildCollisionSkin();
         }
     }
 }
Ejemplo n.º 28
0
 public override void AssignChildComponents(XComponent parent, ref List <uint> children)
 {
     foreach (uint childID in children)
     {
         XComponent child = X.Tools.GetXComponentByID(childID);
         if (child.GetType() == typeof(XHeightMap))
         {
             ((XTreeSystem)parent).HeightMap = (XHeightMap)child;
             ((XTreeSystem)parent).Load(X.Content);
             ((XTreeSystem)parent).GenerateTrees(X.DefaultCamera);
         }
     }
 }
Ejemplo n.º 29
0
 public override void AssignChildComponents(XComponent parent, ref List <uint> children)
 {
     if (children.Count == 1)
     {
         XTree      xparent = (XTree)parent;
         XTreeModel child   = (XTreeModel)X.Tools.GetXComponentByID(children[0]);
         if (child.GetType() == typeof(XTreeModel))
         {
             xparent.model_editor = child;
             xparent.Load(X.Content);
         }
     }
 }
Ejemplo n.º 30
0
        private void renderControl1_OnSelectedComponentChange(object sender, XComponent selectedObj)
        {
            properties.SelectedObject = selectedObj;
            tabControl1.SelectTab(1);

            foreach (ListViewItem item in scene.Items)
            {
                if (selectedObj.ComponentID.ToString() == item.SubItems["colID"].Text)
                {
                    item.Selected = true;
                }
            }
        }
Ejemplo n.º 31
0
        //private static void StartOpenOffice()
        //{
        //    Process[] ps = Process.GetProcessesByName("soffice.exe");
        //    if (ps != null)
        //    {
        //        if (ps.Length > 0)
        //            return;
        //        else
        //        {
        //            Process p = new Process();
        //            p.StartInfo.Arguments = "-headless -nofirststartwizard";
        //            p.StartInfo.FileName = "soffice.exe";
        //            p.StartInfo.CreateNoWindow = true;
        //            bool result = p.Start();
        //            if (result == false)
        //                throw new InvalidProgramException("OpenOffice failed to start.");
        //        }
        //    }
        //    else
        //    {
        //        throw new InvalidProgramException("OpenOffice not found.  Is OpenOffice installed?");
        //    }
        //}


        private static XComponent initDocument(XComponentLoader aLoader, string file, string target)
        {
            PropertyValue[] openProps = new PropertyValue[1];
            openProps[0]       = new PropertyValue();
            openProps[0].Name  = "Hidden";
            openProps[0].Value = new uno.Any(true);


            XComponent xComponent = aLoader.loadComponentFromURL(
                file, target, 0,
                openProps);

            return(xComponent);
        }
        /// <summary>
        /// Saves the document.
        /// </summary>
        /// <param name="xComponent"> The x component. </param>
        /// <param name="sourceFile"> The source file. </param>
        /// <param name="destinationFile"> The destination file. </param>
        public static void SaveDocument(XComponent xComponent, string sourceFile, string destinationFile)
        {
            var filterType     = sourceFile.ConvertExtensionToFilterType();
            var propertyValues = new PropertyValue[] {
                new PropertyValue {
                    Name = "Overwrite", Value = new Any(true)
                },                                                               // Setting the flag for overwriting
                new PropertyValue {
                    Name = "FilterName", Value = new Any(filterType)
                }                                                                       // Setting the filter name
            };

            ((XStorable)xComponent).storeToURL(destinationFile, propertyValues);
        }
Ejemplo n.º 33
0
        private void RunMacro(XComponent document, string macroName, object[] macroParam)
        {
            var providerSupplier = (XScriptProviderSupplier)document;
            if (document != null)
            {
                var provider = providerSupplier.getScriptProvider();
                var script = provider.getScript(
                    String.Format("vnd.sun.star.script:{0}?language=Basic&location=document", macroName));

                // Convert macroParam to Any array
                var macroParamAny = Array.ConvertAll(macroParam, item => new Any(item.GetType(), item));
                var param = new Any[] {
                    new Any(macroParamAny.GetType(), macroParamAny)};

                var outParamIndex = new short[0];
                var outParam = new Any[0];

                script.invoke(param, out outParamIndex, out outParam);
            }
        }
 public WriterDocument(XTextDocument xTextDocument, XComponentContext xContext = null, XMultiComponentFactory xMcFactory = null)
 {
     this.xContext = xContext;
     this.xMcFactory = xMcFactory;
     doc = xTextDocument;
 }
 /// <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);
     }
 }
        /// <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);
            }
        }
        /// <summary>
        /// Try to close the document without any saving of modifications.
        /// We can try it only! Controller and/or model of this document
        /// can disagree with that. But mostly they doesn't do so.
        /// </summary>
        /// <param name="xDocument">document which should be clcosed</param>
        public static void CloseDocument(XComponent xDocument)
        {
            try
            {
                // Check supported functionality of the document (model or controller).
                XModel xModel = (XModel)xDocument;

                if (xModel != null)
                {
                    // It's a full featured office document.
                    // Reset the modify state of it and close it.
                    // Note: Model can disagree by throwing a veto exception.
                    XModifiable xModify = (XModifiable)xModel;

                    xModify.setModified(false);
                    xDocument.dispose();
                }
                else
                {
                    // It's a document which supports a controller .. or may by a pure
                    // window only. If it's at least a controller - we can try to
                    // suspend him. But - he can disagree with that!
                    XController xController = (XController)xDocument;

                    if (xController != null)
                    {
                        if (xController.suspend(true))
                        {
                            // Note: Don't dispose the controller - destroy the frame
                            // to make it right!
                            XFrame xFrame = xController.getFrame();
                            xFrame.dispose();
                        }
                    }
                }
            }
            catch (PropertyVetoException exVeto)
            {
                // Can be thrown by "setModified()" call on model.
                // He disagree with our request.
                // But there is nothing to do then. Following "dispose()" call wasn't
                // never called (because we catch it before). Closing failed -that's it.
                System.Diagnostics.Debug.WriteLine(exVeto);
            }
            catch (DisposedException exDisposed)
            {
                // If an UNO object was already disposed before - he throw this special
                // runtime exception. Of course every UNO call must be look for that -
                // but it's a question of error handling.
                // For demonstration this exception is handled here.
                System.Diagnostics.Debug.WriteLine(exDisposed);
            }
            catch (RuntimeException exRuntime)
            {
                // Every uno call can throw that.
                // Do nothing - closing failed - that's it.
                System.Diagnostics.Debug.WriteLine(exRuntime);
            }
        }
Ejemplo n.º 38
0
        void PerformLoad()
        {
            // Start LibreOffice and load file
            unoidl.com.sun.star.uno.XComponentContext localContext = uno.util.Bootstrap.bootstrap();
            unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.getServiceManager();
            desktop = (XDesktop)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");
            var componentLoader = (XComponentLoader)desktop;
            component = componentLoader.loadComponentFromURL(CreateFileUrl(file.FullName), "_blank", 0, new PropertyValue[] { });

            // TODO: while/before loading, set the viewsettings ViewId:=view1, PageKind:=0 to reset to the default view
            // (instead of notes or outline view). Unfortunately these settings aren't accesible in the API ...

            // Get the main window's handle and hide the window
            document = (XModel)component;
            XWindow window = document.getCurrentController().getFrame().getContainerWindow();
            window.setVisible(false);
            XSystemDependentWindowPeer xWindowPeer = (XSystemDependentWindowPeer)(window);
            mainHandle = new IntPtr((int)xWindowPeer.getWindowHandle(new byte[] { }, SystemDependent.SYSTEM_WIN32).Value);
            //ShowWindow(mainHandle, 0);

            presentation = (XPresentation2)((XPresentationSupplier)component).getPresentation();

            CreateThumbnails();

            listener.SlideTransitionStarted += (sender, args) =>
            {
                OnSlideIndexChanged();
            };

            Start();
            controller.gotoSlideIndex(0);

            LoadPreviewProvider();

            base.OnLoaded(true);
        }
 public WriterDocument(XComponentContext xContext = null, XMultiComponentFactory xMcFactory = null)
 {
     this.xContext = xContext;
     this.xMcFactory = xMcFactory;
     doc = OOoDocument.OpenNewDocumentComponent(OO.DocTypes.SWRITER, xContext, xMcFactory);
 }
Ejemplo n.º 40
0
 /** ctor.
     
     @param obj target object
 */
 public DisposeGuard( XComponent obj )
 {
     m_xComponent = obj;
 }