Esempio n. 1
0
 public virtual void Disconnect()
 {
     SocketUtils.Disconnect();
     Logger.Debug("disconnecting");
     _expectingDisconnection = true;
     _bridgeComponent.dispose();
 }
Esempio n. 2
0
        public override void Close()
        {
            Area.WindowSizeChanged -= Area_WindowSizeChanged;
            Task.Factory.StartNew(() => {
                try
                {
                    if (presentation != null)
                    {
                        presentation.end();
                    }
                    if (component != null)
                    {
                        component.dispose();
                    }
                    if (desktop != null && desktop.getCurrentComponent() == null)                     // no component is running anymore
                    {
                        desktop.terminate();
                    }
                }
                catch (DisposedException)
                {
                    // ignore
                }
            }).ContinueWith((t) =>
            {
                controller = null;

                base.Close();
            });
        }
Esempio n. 3
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(); }
        }
Esempio n. 4
0
 /** System.IDisposable impl
  */
 public void Dispose()
 {
     if (null != m_xComponent)
     {
         m_xComponent.dispose();
     }
 }
Esempio n. 5
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();
         }
     }
 }
Esempio n. 6
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();
            }
        }
Esempio n. 7
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);
            }
        }
        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);
        }
Esempio n. 9
0
        public static void ConvertToPdf(string inputFile, string outputFile)
        {
            if (GetFilterType(Path.GetExtension(inputFile)) == null)
            {
                throw new InvalidProgramException("Unknown file type for OpenOffice. File = " + inputFile);
            }


            XComponent xComponent = null;

            try
            {
                Start();

                //var xLocalContext = Bootstrap.defaultBootstrap_InitialComponentContext();
                //var xLocalServiceManager = xLocalContext.getServiceManager();
                //var xUrlResolver = (XUnoUrlResolver)xLocalServiceManager.createInstanceWithContext(
                //    "com.sun.star.bridge.UnoUrlResolver", xLocalContext);

                var bootstrap = Bootstrap.defaultBootstrap_InitialComponentContext();
                // ReSharper disable once SuspiciousTypeConversion.Global
                var remoteFactory = (XMultiServiceFactory)bootstrap.getServiceManager();
                var aLoader       = (XComponentLoader)remoteFactory.createInstance("com.sun.star.frame.Desktop");

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

                // save/export the document
                SaveDocument(xComponent, inputFile, outputFile);
            }
            finally
            {
                xComponent?.dispose();

                if (_libreOfficeProcess != null)
                {
                    _libreOfficeProcess.Kill();
                    _libreOfficeProcess = null;
                }
            }
        }
Esempio n. 10
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();
            }
        }
Esempio n. 11
0
        private static void ConvertToPdf(string filePath)
        {
            Process[] ps = Process.GetProcessesByName("soffice.exe");
            if (ps.Length != 0)
            {
                throw new InvalidProgramException("OpenOffice not found.  Is OpenOffice installed?");
            }
            if (ps.Length > 0)
            {
                return;
            }
            Process p = new Process
            {
                StartInfo =
                {
                    Arguments      = "-headless -nofirststartwizard",
                    FileName       = "soffice.exe",
                    CreateNoWindow = true
                }
            };
            bool result = p.Start();

            if (result == false)
            {
                throw new InvalidProgramException("OpenOffice failed to start.");
            }
            XComponentContext    xLocalContext  = Bootstrap.bootstrap();
            XMultiServiceFactory xRemoteFactory = (XMultiServiceFactory)xLocalContext.getServiceManager();
            XComponentLoader     aLoader        = (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");
            XComponent           xComponent     = null;

            try
            {
                PropertyValue[] openProps = new PropertyValue[1];
                openProps[0] = new PropertyValue {
                    Name = "Hidden", Value = new Any(true)
                };
                xComponent = aLoader.loadComponentFromURL(PathConverter(filePath), "_blank", 0, openProps);
                while (xComponent == null)
                {
                    Thread.Sleep(1000);
                }
                PropertyValue[] propertyValues = new PropertyValue[2];
                propertyValues[1] = new PropertyValue {
                    Name = "Overwrite", Value = new Any(true)
                };
                propertyValues[0] = new PropertyValue {
                    Name = "FilterName", Value = new Any(ConvertExtensionToFilterType(Path.GetExtension(filePath)))
                };
                ((XStorable)xComponent).storeToURL(PathConverter(OutputFolder + Path.GetFileNameWithoutExtension(filePath) + ".pdf"), propertyValues);
            }
            catch (System.Exception e)
            {
                log.Error("Eccezione la conversione del file OpenOffice " + filePath);
                log.Error(e.StackTrace);
                File.Move(filePath, ErrorFolder + Path.GetFileName(filePath));
            }
            finally
            {
                if (xComponent != null)
                {
                    xComponent.dispose();
                }
                CloseProcess("soffice");
                File.Delete(filePath);
            }
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            InitOpenOfficeEnvironment();
            XMultiServiceFactory multiServiceFactory = Connect();
            XComponent           xComponent          = null;

            string docFileName = @"C:\test3.doc";

            try
            {
                XComponentLoader componentLoader =
                    (XComponentLoader)multiServiceFactory
                    .createInstance("com.sun.star.frame.Desktop");
                //set the property
                PropertyValue[] propertyValue = new PropertyValue[1];
                PropertyValue   aProperty     = new PropertyValue();
                aProperty.Name   = "Hidden";
                aProperty.Value  = new uno.Any(false);
                propertyValue[0] = aProperty;
                xComponent       =
                    componentLoader
                    .loadComponentFromURL(PathConverter(docFileName),
                                          "_blank", 0, propertyValue);
                XTextDocument      xTextDocument      = ((XTextDocument)xComponent);
                XEnumerationAccess xEnumerationAccess =
                    (XEnumerationAccess)xTextDocument.getText();
                XEnumeration xParagraphEnumeration =
                    xEnumerationAccess.createEnumeration();
                while (xParagraphEnumeration.hasMoreElements())
                {
                    uno.Any      element = xParagraphEnumeration.nextElement();
                    XServiceInfo xinfo   = (XServiceInfo)element.Value;
                    if (xinfo.supportsService("com.sun.star.text.TextTable"))
                    {
                        Console.WriteLine("Found Table!");

                        XTextTable xTextTable = (XTextTable)element.Value;
                        String[]   cellNames  = xTextTable.getCellNames();

                        for (int i = 0; i < cellNames.Length; i++)
                        {
                            XCell  xCell     = xTextTable.getCellByName(cellNames[i]);
                            XText  xTextCell = (XText)xCell;
                            String strText   = xTextCell.getString();
                            Console.WriteLine(strText);
                        }
                    }
                    else
                    {
                        XTextContent       xTextElement           = (XTextContent)element.Value;
                        XEnumerationAccess xParaEnumerationAccess =
                            (XEnumerationAccess)xTextElement;
                        // create another enumeration to get all text portions of
                        //the paragraph
                        XEnumeration xTextPortionEnum =
                            xParaEnumerationAccess.createEnumeration();
                        //step 3  Through the Text portions Enumeration, get interface
                        //to each individual text portion
                        while (xTextPortionEnum.hasMoreElements())
                        {
                            XTextRange xTextPortion =
                                (XTextRange)xTextPortionEnum.nextElement().Value;
                            Console.Write(xTextPortion.getString());
                        }
                    }
                }
            }
            catch (unoidl.com.sun.star.uno.Exception exp1)
            {
                Console.WriteLine(exp1.Message);
                Console.WriteLine(exp1.StackTrace);
            }
            catch (System.Exception exp2)
            {
                Console.WriteLine(exp2.Message);
                Console.WriteLine(exp2.StackTrace);
            }
            finally
            {
                xComponent.dispose();
                xComponent = null;
            }
            Console.WriteLine("Done.");
            Console.ReadLine();
        }
Esempio n. 13
0
        public byte[] Convert(byte[] fileSource, string fileExtension, string extReq, AttachConversionMode mode)
        {
            logger.DebugFormat("Convert {0} to {1}", fileExtension, extReq);
            string fileName = Path.GetTempFileName();

            try
            {
                return(RetryingPolicyAction <byte[]>(() => {
                    File.WriteAllBytes(fileName + fileExtension, fileSource);
                    if (localContext == null)
                    {
                        localContext = uno.util.Bootstrap.bootstrap();
                    }

                    unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.getServiceManager();
                    XComponentLoader componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");

                    PropertyValue[] propertyValue = new PropertyValue[2];
                    PropertyValue aProperty = new PropertyValue();
                    aProperty.Name = "Hidden";
                    aProperty.Value = new uno.Any(true);
                    propertyValue[0] = aProperty;

                    propertyValue[1] = new PropertyValue();
                    propertyValue[1].Name = "IsSkipEmptyPages";
                    propertyValue[1].Value = new uno.Any(true);

                    XComponent xComponent = null;
                    bool toConvert = false;
                    string fileConvertedName;
                    try
                    {
                        string fileToConvertName = PathConverter(fileName + fileExtension);
                        fileConvertedName = PathConverter(fileName + "." + extReq);
                        logger.DebugFormat("Url to comvert: {0} - {1}", fileToConvertName, fileConvertedName);
                        xComponent = componentLoader.loadComponentFromURL(
                            fileToConvertName,
                            "_blank",
                            0,
                            propertyValue
                            );
                        if (xComponent == null)
                        {
                            throw new DocumentNotConvertible_Exception();
                        }

                        logger.Debug("Verify if is to process...");
                        if (fileExtension.Contains("doc") && (UseRedirectMethod(xComponent)))
                        {
                            logger.Debug("No conversion to do...");
                            toConvert = true;
                        }
                        else
                        {
                            object xls = null;

                            if (xComponent is XSpreadsheetDocument)
                            {
                                xls = xComponent as XSpreadsheetDocument;
                            }
                            else if (xComponent is XTextDocument)
                            {
                                xls = xComponent as XTextDocument;
                            }

                            if (xls != null)
                            {
                                //Se i nomi degli sheets sono fra quelli non convertibili, usare il converter Office.
                                if (xls is XSpreadsheetDocument)
                                {
                                    var sheetNames = (xls as XSpreadsheetDocument)
                                                     .getSheets()
                                                     .getElementNames()
                                                     .ToArray();

                                    for (int i = 0; i < sheetNames.Length; i++)
                                    {
                                        sheetNames[i] = (sheetNames[i] ?? string.Empty).ToUpper();
                                    }

                                    var namesSet = (ConfigurationManager.AppSettings["RedirectSheetNames"] ?? string.Empty)
                                                   .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                                                   .OrderByDescending(x => x.Length);

                                    var founded = false;

                                    foreach (var set in namesSet)
                                    {
                                        var names = set
                                                    .Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                                        if (names.Length <= sheetNames.Length)
                                        {
                                            founded = true;
                                            foreach (var n in names)
                                            {
                                                if (!sheetNames.Contains(n.ToUpper()))
                                                {
                                                    founded = false;
                                                    break;
                                                }
                                            }

                                            if (founded)
                                            {
                                                logger.Debug("No conversion to do...");
                                                return null;
                                            }
                                        }
                                    }
                                }

                                //var xls = xComponent as XSpreadsheetDocument;
                                var styles = (xls as XStyleFamiliesSupplier).getStyleFamilies();
                                var pageStyles = styles.getByName("PageStyles").Value as XNameContainer;

                                bool scaleToPages = false;

                                var configured = ConfigurationManager.AppSettings["ScaleToPages"];
                                try
                                {
                                    if (!string.IsNullOrEmpty(configured))
                                    {
                                        var dummy = bool.Parse(configured);
                                        scaleToPages = dummy;
                                    }
                                }
                                catch { logger.ErrorFormat("Invalid value for configured parameter \"{0}\". Current value is \"{1}\".", "ScaleToPages", configured); }

                                var configValue = ConfigurationManager.AppSettings["StampaConforme.ForcePortrait"];
                                var forcePortrait = !string.IsNullOrEmpty(configValue) && configValue.Equals("true", StringComparison.InvariantCultureIgnoreCase);
                                logger.Info("StampaConforme.ForcePortrait: " + forcePortrait.ToString());

                                foreach (var nome in pageStyles.getElementNames())
                                {
                                    var props = pageStyles.getByName(nome).Value as XPropertySet;
                                    if (forcePortrait)
                                    {
                                        var isLandscape = (bool)props.getPropertyValue("IsLandscape").Value;
                                        if (isLandscape)
                                        {
                                            var size = props.getPropertyValue("Size").Value as Size;
                                            var w = size.Width;
                                            size.Width = size.Height;
                                            size.Height = w;
                                            props.setPropertyValue("Size", new uno.Any(typeof(Size), size));
                                            props.setPropertyValue("IsLandscape", new uno.Any(false));
                                        }
                                    }

                                    if (scaleToPages && props.getPropertySetInfo().hasPropertyByName("ScaleToPages"))
                                    {
                                        props.setPropertyValue("ScaleToPages", new uno.Any((short)1));
                                    }
                                }
                            }

                            PropertyValue[] saveProps = new PropertyValue[2];
                            saveProps[0] = new PropertyValue();
                            saveProps[0].Name = "FilterName";
                            saveProps[0].Value = new uno.Any("writer_pdf_Export");

                            saveProps[1] = new PropertyValue();
                            saveProps[1].Name = "IsSkipEmptyPages";
                            saveProps[1].Value = new uno.Any(true);
                            logger.Debug("loadComponentFromURL end.");

                            ((XStorable)xComponent).storeToURL(fileConvertedName, saveProps);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                        throw;
                    }
                    finally
                    {
                        if (xComponent != null)
                        {
                            xComponent.dispose();
                        }
                    }
                    logger.DebugFormat("Conversione END - ToConvert: {0}", toConvert);
                    if (toConvert)
                    {
                        return null;
                    }
                    else
                    {
                        return File.ReadAllBytes(fileName + "." + extReq);
                    }
                }));
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw;
            }
            finally
            {
                try
                {
                    File.Delete(fileName + fileExtension);
                    File.Delete(fileName + extReq);
                    File.Delete(fileName);
                }
                catch { }
            }
        }
        /// <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);
            }
        }
        public string PdfGenerator([FromBody] string[] lstfullpath)
        {
            var statuscode    = "";
            var strFullPath   = string.Join("\\", lstfullpath);
            var strReportPath = @"C:\ALISS_ProcessFile";

            var query = new List <sp_GET_TCParameter_Result>();

            query = db.sp_GET_TCParameter("RPT_PROCESS_PATH").ToList();

            if (query.FirstOrDefault(x => x.prm_code_minor == "PATH") != null)
            {
                strReportPath = query.FirstOrDefault(x => x.prm_code_minor == "PATH").prm_value;
            }

            var inputFile  = Path.Combine(strReportPath, strFullPath);
            var outputFile = Path.Combine(strReportPath, strFullPath.Replace(Path.GetExtension(inputFile), ".pdf"));

            //string outputFile = @"D:\TestDownload\pdf\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";
            }
            finally
            {
                if (xComponent != null)
                {
                    xComponent.dispose();
                }
            }
            return(statuscode);
        }
Esempio n. 16
0
        public void CozdSchetWriter(string push, int ID)
        {
            DB5  db   = new DB5(kursach.Program.Pole.pole);
            DB16 db2  = new DB16(kursach.Program.Pole.pole);
            DB1  db1  = new DB1(kursach.Program.Pole.pole);
            DB14 db14 = new DB14(kursach.Program.Pole.pole);
            DB13 db13 = new DB13(kursach.Program.Pole.pole);

            Mapping.DB17 db17 = new Mapping.DB17(kursach.Program.Pole.pole);
            var          ec   = from n in db.JurnalRabot
                                where n.ID == Convert.ToInt32(ID)
                                select n;
            int temp = 0;

            foreach (var i in ec)
            {
                temp = i.IDZapisi;
            }
            var ec2 = from n in db2.Zapis
                      where n.ID == temp
                      select n;
            var Firma = from n in db17.Firma
                        where n.ID == 1
                        select n;
            string temp2 = "";

            foreach (var i in ec2)
            {
                temp2 = i.Data;
            }
            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();
            XComponentLoader componentLoader = (XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");
            XComponent       xComponent      = componentLoader.loadComponentFromURL("private:factory/swriter", "_blank", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);

            ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().setString("Счет №" + ID + Environment.NewLine);

            unoidl.com.sun.star.text.XTextRange x = ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().getEnd();  // в конец
            ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().insertString(x, "от " + temp2 + "г." + Environment.NewLine + Environment.NewLine + Environment.NewLine, true);
            unoidl.com.sun.star.text.XTextRange xi = ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().getEnd(); // в конец
            foreach (var i in Firma)
            {
                ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().insertString(xi, "ИНН " + i.INN + " КПП " + i.KPP + Environment.NewLine + "Получатель " + i.Name + " № Счета " + i.Schet + Environment.NewLine + "Банк получателя " + i.Bank + " № Счета банка " + i.SchetBank + Environment.NewLine, true);
            }

            DB11 db11       = new DB11(kursach.Program.Pole.pole);
            var  Raspisanie = from n in db11.Raspisanie
                              where n.ID == temp
                              select n;

            foreach (var i in Raspisanie)
            {
                temp = i.IDVrach;
            }
            var Vrach = from n in db14.Vrach
                        where n.ID == temp
                        select n;

            foreach (var i in Vrach)
            {
                temp2 = i.FIO;
            }
            unoidl.com.sun.star.text.XTextRange x2 = ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().getEnd();  // в конец
            ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().insertString(x2, "Исполнитель: " + temp2 + Environment.NewLine, true);

            foreach (var i in ec2)
            {
                temp = i.IDPacienta;
            }
            var ec3 = from n in db1.Pacient
                      where n.ID == temp
                      select n;

            foreach (var i in ec3)
            {
                temp2 = i.FIO;
            }
            unoidl.com.sun.star.text.XTextRange x3 = ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().getEnd();  // в конец
            ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().insertString(x3, "Заказчик: " + temp2 + Environment.NewLine + Environment.NewLine + Environment.NewLine, true);

            //Таблица
            XFrame          frame           = ((unoidl.com.sun.star.text.XTextDocument)xComponent).getCurrentController().getFrame();
            XDispatchHelper xDispatchHelper = (XDispatchHelper)multiServiceFactory.createInstance("com.sun.star.frame.DispatchHelper");

            unoidl.com.sun.star.beans.PropertyValue[] tableArgs = new unoidl.com.sun.star.beans.PropertyValue[4];
            tableArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            tableArgs[1]       = new unoidl.com.sun.star.beans.PropertyValue();
            tableArgs[2]       = new unoidl.com.sun.star.beans.PropertyValue();
            tableArgs[3]       = new unoidl.com.sun.star.beans.PropertyValue();
            tableArgs[0].Name  = "TableName";
            tableArgs[0].Value = new uno.Any("Акт");
            tableArgs[1].Name  = "Columns";
            tableArgs[1].Value = new uno.Any(4);
            tableArgs[2].Name  = "Rows";
            tableArgs[2].Value = new uno.Any(2);
            tableArgs[3].Name  = "Flags";
            tableArgs[3].Value = new uno.Any(9);
            unoidl.com.sun.star.beans.PropertyValue[] cellTextArgs =
                new unoidl.com.sun.star.beans.PropertyValue[1];
            cellTextArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            cellTextArgs[0].Name  = "Text";
            cellTextArgs[0].Value = new uno.Any("Наименование Услуги");
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertTable", "", 0, tableArgs);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs);
            unoidl.com.sun.star.beans.PropertyValue[] cellTextArgs2 =
                new unoidl.com.sun.star.beans.PropertyValue[1];
            cellTextArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            cellTextArgs[0].Name  = "Text";
            cellTextArgs[0].Value = new uno.Any("Цена");
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs2);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:JumpToNextCell", "", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs);
            unoidl.com.sun.star.beans.PropertyValue[] cellTextArgs3 =
                new unoidl.com.sun.star.beans.PropertyValue[1];
            cellTextArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            cellTextArgs[0].Name  = "Text";
            cellTextArgs[0].Value = new uno.Any("Скидка");
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs3);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:JumpToNextCell", "", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs);
            unoidl.com.sun.star.beans.PropertyValue[] cellTextArgs4 =
                new unoidl.com.sun.star.beans.PropertyValue[1];
            cellTextArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            cellTextArgs[0].Name  = "Text";
            cellTextArgs[0].Value = new uno.Any("Итого");
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs4);

            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:JumpToNextCell", "", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs);
            foreach (var i in ec2)
            {
                temp = i.IDUslugi;
            }
            var ec5 = from n in db13.Uslugi
                      where n.ID == temp
                      select n;

            foreach (var i in ec5)
            {
                temp2 = i.Name;
            }
            unoidl.com.sun.star.beans.PropertyValue[] cellTextArgs5 =
                new unoidl.com.sun.star.beans.PropertyValue[1];
            cellTextArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            cellTextArgs[0].Name  = "Text";
            cellTextArgs[0].Value = new uno.Any(temp2);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs5);

            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:JumpToNextCell", "", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs);
            foreach (var i in ec)
            {
                temp2 = i.Cena.ToString();
            }
            unoidl.com.sun.star.beans.PropertyValue[] cellTextArgs6 =
                new unoidl.com.sun.star.beans.PropertyValue[1];
            cellTextArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            cellTextArgs[0].Name  = "Text";
            cellTextArgs[0].Value = new uno.Any(temp2);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs6);

            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:JumpToNextCell", "", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs);
            foreach (var i in ec)
            {
                temp2 = i.Skidka.ToString();
            }
            unoidl.com.sun.star.beans.PropertyValue[] cellTextArgs7 =
                new unoidl.com.sun.star.beans.PropertyValue[1];
            cellTextArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            cellTextArgs[0].Name  = "Text";
            cellTextArgs[0].Value = new uno.Any(temp2);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs7);

            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:JumpToNextCell", "", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs);
            foreach (var i in ec)
            {
                temp2 = i.Itog.ToString();
            }
            unoidl.com.sun.star.beans.PropertyValue[] cellTextArgs8 =
                new unoidl.com.sun.star.beans.PropertyValue[1];
            cellTextArgs[0]       = new unoidl.com.sun.star.beans.PropertyValue();
            cellTextArgs[0].Name  = "Text";
            cellTextArgs[0].Value = new uno.Any(temp2);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs8);

            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:JumpToNextCell", "", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);
            xDispatchHelper.executeDispatch((XDispatchProvider)frame, ".uno:InsertText", "", 0, cellTextArgs);

            unoidl.com.sun.star.text.XTextRange x4 = ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().getEnd();  // в конец
            ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().insertString(x4, "Всего оказано услуг на сумму: " + temp2 + "рублей " + Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine, true);
            string temp3 = "";

            foreach (var i in Vrach)
            {
                temp2 = i.FIO;
            }
            foreach (var i in ec3)
            {
                temp3 = i.FIO;
            }
            unoidl.com.sun.star.text.XTextRange x5 = ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().getEnd();  // в конец
            foreach (var i in Firma)
            {
                ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().insertString(x5, "Исполнитель:__________________ " + temp2 + Environment.NewLine + "Бухгалтер:__________________" + i.Buh, true);
            }
            ((XStorable)xComponent).storeToURL(@"file:///" + push.Replace(@"\", "/"), new unoidl.com.sun.star.beans.PropertyValue[0]);
            xComponent.dispose();
        }
        public static XControlContainer createDialog(XMultiComponentFactory xMultiComponentFactory, XComponentContext xContext,
                                                     int posX, int posY, int width, int height, string title
                                                     )
        {
            //dialog model
            Object oDialogModel = xMultiComponentFactory.createInstanceWithContext(
                "com.sun.star.awt.UnoControlDialogModel", xContext);


            XPropertySet xPSetDialog = (XPropertySet)oDialogModel;

            xPSetDialog.setPropertyValue("PositionX", Any.Get(posX));
            xPSetDialog.setPropertyValue("PositionY", Any.Get(posY));
            xPSetDialog.setPropertyValue("Width", Any.Get(width));
            xPSetDialog.setPropertyValue("Height", Any.Get(height));
            xPSetDialog.setPropertyValue("Title", Any.Get(title));

            // get service manager from  dialog model
            XMultiServiceFactory MXMsfDialogModel = (XMultiServiceFactory)oDialogModel;

            // dialog control model
            Object oUnoDialog = xMultiComponentFactory.createInstanceWithContext(
                "com.sun.star.awt.UnoControlDialog", xContext);


            XControl      MXDialogControl = (XControl)oUnoDialog;
            XControlModel xControlModel   = (XControlModel)oDialogModel;

            MXDialogControl.setModel(xControlModel);



            XToolkit xToolkit = (XToolkit)xMultiComponentFactory
                                .createInstanceWithContext("com.sun.star.awt.Toolkit",
                                                           xContext);

            WindowDescriptor aDescriptor = new WindowDescriptor();

            aDescriptor.Type = WindowClass.TOP;
            aDescriptor.WindowServiceName = "";
            aDescriptor.ParentIndex       = -1;
            aDescriptor.Parent            = xToolkit.getDesktopWindow();
            aDescriptor.Bounds            = new Rectangle(100, 200, 300, 400);

            aDescriptor.WindowAttributes = WindowAttribute.BORDER
                                           | WindowAttribute.MOVEABLE | WindowAttribute.SIZEABLE
                                           | WindowAttribute.CLOSEABLE;

            XWindowPeer xPeer = xToolkit.createWindow(aDescriptor);

            XWindow xWindow = (XWindow)xPeer;

            xWindow.setVisible(false);
            MXDialogControl.createPeer(xToolkit, xPeer);

            // execute the dialog
            XDialog xDialog = (XDialog)oUnoDialog;

            xDialog.execute();

            // dispose the dialog
            XComponent xComponent = (XComponent)oUnoDialog;

            xComponent.dispose();

            return(oUnoDialog as XControlContainer);
        }
Esempio n. 18
0
 public void Close()
 {
     doc.dispose();
     doc = null;
 }
Esempio n. 19
0
        /// <summary>
        ///     Converts the given <paramref name="inputFile" /> to PDF format and saves it as <paramref name="outputFile" />
        /// </summary>
        /// <param name="inputFile">The input file</param>
        /// <param name="outputFile">The output file</param>
        public void ConvertToPdf(string inputFile, string outputFile)
        {
            if (GetFilterType(Path.GetExtension(inputFile)) == null)
            {
                throw new InvalidProgramException("Unknown file type for OpenOffice. File = " + inputFile);
            }

            XComponent component = null;

            try
            {
                var guid = Guid.NewGuid().ToString().Replace("-", string.Empty);
                _userFolder = $"d:/{guid}";
                _pipeName   = guid;
                //_pipeName = "keeshispipe";
                //Directory.CreateDirectory(_userFolder);

                Start();

                var localContext        = Bootstrap.defaultBootstrap_InitialComponentContext();
                var localServiceManager = localContext.getServiceManager();
                var urlResolver         =
                    (XUnoUrlResolver)localServiceManager.createInstanceWithContext(
                        "com.sun.star.bridge.UnoUrlResolver", localContext);
                XComponentContext remoteContext;

                var i = 0;

                while (true)
                {
                    try
                    {
                        remoteContext =
                            (XComponentContext)urlResolver.resolve(
                                $"uno:pipe,name={_pipeName};urp;StarOffice.ComponentContext");

                        break;
                    }
                    catch (Exception exception)
                    {
                        if (i == 20 || !exception.Message.Contains("couldn't connect to pipe"))
                        {
                            throw;
                        }
                        Thread.Sleep(100);
                        i++;
                    }
                }

                // ReSharper disable once SuspiciousTypeConversion.Global
                var remoteFactory   = (XMultiServiceFactory)remoteContext.getServiceManager();
                var componentLoader = (XComponentLoader)remoteFactory.createInstance("com.sun.star.frame.Desktop");
                component = InitDocument(componentLoader, ConvertToUrl(inputFile), "_blank");

                // Save/export the document
                // http://herbertniemeyerblog.blogspot.com/2011/11/have-to-start-somewhere.html
                // https://forum.openoffice.org/en/forum/viewtopic.php?t=73098

                ExportToPdf(component, inputFile, outputFile);

                CloseDocument(component);
            }
            finally
            {
                component?.dispose();

                if (_libreOfficeProcess != null && !_libreOfficeProcess.HasExited)
                {
                    _libreOfficeProcess.Kill();

                    while (!_libreOfficeProcess.HasExited)
                    {
                        Thread.Sleep(100);
                    }

                    _libreOfficeProcess = null;
                }

                try
                {
                    if (!string.IsNullOrEmpty(_userFolder))
                    {
                        Directory.Delete(_userFolder, true);
                    }
                }
                catch
                {
                }
            }
        }