Sunday, June 13, 2010

Automating OO From .NET

This was an interesting experience, I am a lot more comfortable developing in visual studio but for OO Netbeans has been much easier.

Here is the source:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using Microsoft.Win32;
using System.IO;
using System.Runtime.InteropServices;
using unoidl.com.sun.star.frame;


namespace ConsoleApplication1
{
class TestOO
{
public int run()
{
InitOpenOfficeEnvironment();
unoidl.com.sun.star.uno.XComponentContext localContent = uno.util.Bootstrap.bootstrap();
unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)localContent.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("Automating OO");


return 0;
}
private void InitOpenOfficeEnvironment()
{
string baseKey;
// 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 + @"LayerDev\URE\1";
RegistryKey reg = Registry.CurrentUser.OpenSubKey(key);
if (reg == null) reg = Registry.LocalMachine.OpenSubKey(key);
string urePath = @"C:\Program Files\OOo-dev 3\URE\bin";
reg.Close();
urePath = Path.Combine(urePath, "bin");

// Get the UNO Path
key = baseKey + @"UNO\InstallPath";
reg = Registry.CurrentUser.OpenSubKey(key);
if (reg == null) reg = Registry.LocalMachine.OpenSubKey(key);
string unoPath = @"C:\Program Files\OOo-dev 3\program";
//reg.Close();

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

}

This is a console app that when runs opens an instance of open office writer and prints "Automating OO".

The InitOpenOfficeEnvironment() method was code that I found here: http://blog.nkadesign.com/2008/net-working-with-openoffice-3/ and it sets up the path and uno_path environment variables so that open office can run. You could also set your paths manually but this allows for distribution. I had a lot of trouble getting the path from the registry as the code was originally for the openoffice 3 and not oo3 dev.

The next part of the code uses the factory style of programming to allow for easier development. It instantiates an openoffice writer and sets the text.

No comments:

Post a Comment