Tuesday, 17 February 2015

Open office document- Everything (or almost) you need for Writer (Open, save, Table, picture...)


//References are: you can find them in the GAC or in the 3.x sdk
//cli_basetypes.dll
//cli_cppuhelper.dll
//cli_oootypes.dll
//cli_uno.dll
//cli_ure.dll
//cli_uretypes.dll

using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Text;
//For Marshal and Registry
using Microsoft.Win32;
/*
* Add all needed CLI namespaces to the current class.
*/
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.text;
using uno.util;

namespace OOOCLI
{
    class OpenOfficeApp
    {
        //Define a file name. Change this to an existing path!
        private static string FileName = @"F:\odtfiles\test.odt";
     
            public static void OOOStart()
        {
            // ***********************    Connection
            //Necessary with OOO3 and NetFramework less than 3.5 (see:
            //   http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/ProUNO/CLI/CLI_Language_Binding
            // & http://blog.nkadesign.com/2008/net-working-with-openoffice-3/ .
            InitOpenOfficeEnvironment();

            //From Lars Behrmann: OpenOffice programming with C# / .net http://www.opendocument4all.com/
         
            // ***********************    First Steps to Load a document
            //Call the bootstrap method to get a new ComponentContext object.
            //If OpenOffice isn't already started this will start it and then return the ComponentContext.
            unoidl.com.sun.star.uno.XComponentContext localContext = uno.util.Bootstrap.bootstrap();

            //Get a new service manager of the MultiServiceFactory type
            //we need this to get a desktop object and create new CLI objects.
            unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContext.getServiceManager();
         
            //Create a new Desktop instance using our service manager
            //Notice: We cast our desktop object to XComponent loader
            //so that we could load or create new documents.
            XComponentLoader componentLoader =(XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop");
         
            //Create a new blank writer document using our component loader object.
            XComponent xComponent = componentLoader.loadComponentFromURL(
            "private:factory/swriter", //a blank writer document
            "_blank", 0, //into a blank frame use no searchflag
            new unoidl.com.sun.star.beans.PropertyValue[0]);//use no additional arguments.

            // ***********************    Working with text
            // -------------------      First and simple Method
            //Cast our component to a the XText interface
         
            //and write some simple text into document.
           // ((unoidl.com.sun.star.text.XTextDocument)xComponent).getText().setString("Hello I'm the first text!");

            // From sdk WriterDemo.vb translate and enhanced to C# by Marc FEGLI http://pagesperso-orange.fr/hffm/index.html
            // -------------------      Second and complete Method
            ////Cast our component to a the XText interface: Create a text object
            XText xText = ((XTextDocument)xComponent).getText();
            XSimpleText xSimpleText = (XSimpleText)xText;

            //Create a cursor object
            XTextCursor xCursor = xSimpleText.createTextCursor();
            // C# characters for Backspace ... "\r" and "\n"
            //Inserting some Text
            xText.insertString(xCursor, "The first line in the newly created text document." + "\r", false);

            //Create instance of a text table with 4 columns and 4 rows
            object objTextTable = null;
            objTextTable = ((XMultiServiceFactory)xComponent).createInstance("com.sun.star.text.TextTable");
            XTextTable xTextTable = (XTextTable)objTextTable;
            xTextTable.initialize(4, 4);
            xText.insertTextContent(xCursor, xTextTable, false);


            //Set the table background color
            // Get XPropertySet interfaces from Table object
            unoidl.com.sun.star.beans.XPropertySet xPropertySetTable = (unoidl.com.sun.star.beans.XPropertySet)objTextTable;
            xPropertySetTable.setPropertyValue("BackTransparent", new uno.Any(false));
            xPropertySetTable.setPropertyValue("BackColor", new uno.Any(0xccccff));

            //Get first row
            unoidl.com.sun.star.table.XTableRows xTableRows = xTextTable.getRows();
            uno.Any anyRow = default(uno.Any);
            anyRow = ((unoidl.com.sun.star.container.XIndexAccess)xTableRows).getByIndex(0);

            //Set a different background color for the first row
            // Get XPropertySet interface from Row object
            unoidl.com.sun.star.beans.XPropertySet xPropertySetFirstRow = (unoidl.com.sun.star.beans.XPropertySet)anyRow.Value;
            xPropertySetFirstRow.setPropertyValue("BackTransparent", new uno.Any(false));
            xPropertySetFirstRow.setPropertyValue("BackColor", new uno.Any(0x6666aa));
         
            //Fill the first table row
            //Delegate Methods: see insertIntoCell
            insertIntoCell("A1", "FirstColumn", xTextTable);
            insertIntoCell("B1", "SecondColumn", xTextTable);
            insertIntoCell("C1", "ThirdColumn", xTextTable);
            insertIntoCell("D1", "SUM", xTextTable);

            //Fill the remaining rows
            xTextTable.getCellByName("A2").setValue(22.5);
            xTextTable.getCellByName("B2").setValue(5615.3);
            xTextTable.getCellByName("C2").setValue(-2315.7);
            xTextTable.getCellByName("D2").setFormula("sum <A2:C2>");

            xTextTable.getCellByName("A3").setValue(21.5);
            xTextTable.getCellByName("B3").setValue(615.3);
            xTextTable.getCellByName("C3").setValue(-315.7);
            xTextTable.getCellByName("D3").setFormula("sum <A3:C3>");

            xTextTable.getCellByName("A4").setValue(121.5);
            xTextTable.getCellByName("B4").setValue(-615.3);
            xTextTable.getCellByName("C4").setValue(415.7);
            xTextTable.getCellByName("D4").setFormula("sum <A4:C4>");

            //Change the CharColor and add a Shadow
            // Get XPropertySet interface from Cursor object
            unoidl.com.sun.star.beans.XPropertySet xPropertySetCursor = (unoidl.com.sun.star.beans.XPropertySet)xCursor;
            xPropertySetCursor.setPropertyValue("CharColor", new uno.Any(255));
            xPropertySetCursor.setPropertyValue("CharShadowed", new uno.Any(true));

            //Create a paragraph break
            xSimpleText.insertControlCharacter(xCursor, unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false);

            //Inserting colored Text.
            xSimpleText.insertString(xCursor, " This is a colored Text - blue with shadow" + "\r", false);

            //Create a paragraph break
            xSimpleText.insertControlCharacter(xCursor, unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false);

            //Create a GraphicObject.
            object objGraphicObject = null;
            objGraphicObject = ((unoidl.com.sun.star.lang.XMultiServiceFactory)xComponent).createInstance("com.sun.star.text.GraphicObject");

            unoidl.com.sun.star.text.XTextContent xGraphicObject = (unoidl.com.sun.star.text.XTextContent)objGraphicObject;

            //Set the size of the GraphicObject
            unoidl.com.sun.star.awt.Size GraphicObjectSize = new unoidl.com.sun.star.awt.Size(5000, 5000);
            ((unoidl.com.sun.star.drawing.XShape)xGraphicObject).setSize(GraphicObjectSize);

            //Set anchortype
            unoidl.com.sun.star.beans.XPropertySet xPropertySetGraphicObject = (unoidl.com.sun.star.beans.XPropertySet)xGraphicObject;
            xPropertySetGraphicObject.setPropertyValue("AnchorType", new uno.Any(typeof(unoidl.com.sun.star.text.TextContentAnchorType), unoidl.com.sun.star.text.TextContentAnchorType.AS_CHARACTER));

            //Set Picture path:
            // First Method with OOO notation for Windows Notation see PathConverter method
            xPropertySetGraphicObject.setPropertyValue("GraphicURL", new uno.Any("file:///C:/test.jpg"));
         
            //insert the GraphicObject
            xText.insertTextContent(xCursor, xGraphicObject, false);

            //Create a TextFrame.
            object objTextFrame = null;
            objTextFrame = ((unoidl.com.sun.star.lang.XMultiServiceFactory)xComponent).createInstance("com.sun.star.text.TextFrame");

            unoidl.com.sun.star.text.XTextFrame xTextFrame = (unoidl.com.sun.star.text.XTextFrame)objTextFrame;

            //Set the size of the frame
            unoidl.com.sun.star.awt.Size FrameSize = new unoidl.com.sun.star.awt.Size(15000, 400);
            ((unoidl.com.sun.star.drawing.XShape)xTextFrame).setSize(FrameSize);

            //Set anchortype
            unoidl.com.sun.star.beans.XPropertySet xPropertySetFrame = (unoidl.com.sun.star.beans.XPropertySet)xTextFrame;
            xPropertySetFrame.setPropertyValue("AnchorType", new uno.Any(typeof(unoidl.com.sun.star.text.TextContentAnchorType), unoidl.com.sun.star.text.TextContentAnchorType.AS_CHARACTER));

            //insert the frame
            xText.insertTextContent(xCursor, xTextFrame, false);

            //Get the text object of the frame

            unoidl.com.sun.star.text.XText xFrameText = xTextFrame.getText();

            unoidl.com.sun.star.text.XSimpleText xFrameSimpleText = (unoidl.com.sun.star.text.XSimpleText)xFrameText;

            //Create a cursor object
            unoidl.com.sun.star.text.XTextCursor xFrameCursor = xFrameSimpleText.createTextCursor();

            //Inserting some Text
            xFrameSimpleText.insertString(xFrameCursor, "The first line in the newly created text frame.", false);
            xFrameSimpleText.insertString(xFrameCursor, "\r" + "With this second line the height of the frame raises.", false);

            //Create a paragraph break
            xSimpleText.insertControlCharacter(xFrameCursor, unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false);

            //Change the CharColor and add a Shadow
            xPropertySetCursor.setPropertyValue("CharColor", new uno.Any(65536));
            xPropertySetCursor.setPropertyValue("CharShadowed", new uno.Any(false));

            //After we insert our text, we cast our component to XStorable to save it onto the harddisk
            ((XStorable)xComponent).storeToURL(PathConverter(FileName),          //Convert the file path into a OpenOffice path
            //no additional arguments
            new unoidl.com.sun.star.beans.PropertyValue[0]);
            Console.WriteLine("Your first OpenOffice document is saved!");
            Console.ReadLine();
        }
        private static void insertIntoCell(string sCellName, string sText, unoidl.com.sun.star.text.XTextTable xTable)
        {
            unoidl.com.sun.star.table.XCell xCell = xTable.getCellByName(sCellName);

            unoidl.com.sun.star.text.XSimpleText xSimpleTextCell = (unoidl.com.sun.star.text.XSimpleText)xCell;

            unoidl.com.sun.star.text.XTextCursor xCursor = xSimpleTextCell.createTextCursor();

            unoidl.com.sun.star.beans.XPropertySet xPropertySetCursor = (unoidl.com.sun.star.beans.XPropertySet)xCursor;

            xPropertySetCursor.setPropertyValue("CharColor", new uno.Any(0xffffff));
            xSimpleTextCell.insertString(xCursor, sText, false);
        }
        /// <summary>
        /// Convert into OO file format
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>The converted file</returns>
        private static string PathConverter(string file)
        {
            try
            {
                file = file.Replace(@"\", "/");
                return "file:///"+file;
            }catch(System.Exception ex)
            {
                throw ex;
            }
        }

        private static void InitOpenOfficeEnvironment()
        {
            //from http://blog.nkadesign.com/2008/net-working-with-openoffice-3/
            string baseKey = null;
            // OpenOffice being a 32 bit app, its registry location is different in a 64 bit OS
            if ((Marshal.SizeOf(typeof(IntPtr)) == 8))
            {
                baseKey = "SOFTWARE\\Wow6432Node\\OpenOffice.org\\";
            }
            else
            {
                baseKey = "SOFTWARE\\OpenOffice.org\\";
            }

            // Get the URE directory
            string key = (baseKey + "Layers\\URE\\1");
            RegistryKey reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(key);
            if ((reg == null))
            {
                reg = Registry.LocalMachine.OpenSubKey(key);
            }
            string urePath = (string)reg.GetValue("UREINSTALLLOCATION");
            reg.Close();
            urePath = System.IO.Path.Combine(urePath, "bin");
            // Get the UNO Path
            key = (baseKey + "UNO\\InstallPath");
            reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(key);
            if ((reg == null))
            {
                reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(key);
            }
            string unoPath = (string)reg.GetValue(null);
            reg.Close();

            string path = null;
            path = string.Format("{0};{1}", System.Environment.GetEnvironmentVariable("PATH"), urePath);
            System.Environment.SetEnvironmentVariable("PATH", path);
            System.Environment.SetEnvironmentVariable("UNO_PATH", unoPath);
        }
    }

    }

No comments:

Post a Comment