Create Word documents with OpenOffice Writer with C# and .NET

For creating Open Office documents, it is possible to use UNO project with CLI binding for .NET environment and C# language. In following text, reader can find simple example of this approach.

Background

UNO, which stands for Universal Network Objects is component model for OpenOffice. For development with UNO there is an SDK, that allows developers develop with common objects for OpenOffice package.

How to create MS Word 95 .doc file using OpenOffice Writer

First, you need to have OpenOffice with OpenOffice SDK of the same version. I have tested following sample with OpenOffice 3.1.

When you are creating .NET project, you have add references to assemblies from UNO-CLI project. These are on Windows installed in:

C:\Program Files\OpenOffice.org_3.1_SDK\sdk\cli

These assemblies are compiled against .NET 2.0 and therefore you should have your project target set to .NET 2 Framework.

XComponentContext oStrap = uno.util.Bootstrap.bootstrap();
XMultiServiceFactory oServMan = (XMultiServiceFactory)oStrap.getServiceManager();
XComponentLoader oDesk = (XComponentLoader)oServMan.createInstance("com.sun.star.frame.Desktop");
string url = @"private:factory/swriter";
PropertyValue[] propVals = new PropertyValue[0];
            
XComponent oDoc = oDesk.loadComponentFromURL(url, "_blank", 0, propVals);

string docText = "This will be my first paragraph.\n\r";
docText += "This will be my second paragraph.\n\r";
            
            
((XTextDocument)oDoc).getText().setString(docText);

string fileName = @"C:\test.doc";
fileName = "file:///" + fileName.Replace(@"\", "/");

PropertyValue[] savePropVals = new PropertyValue[1];
savePropVals[0] = new PropertyValue("FilterName", 0, new uno.Any("MS Word 97"), PropertyState.DIRECT_VALUE);
((XStorable)oDoc).storeAsURL(fileName, savePropVals);
((XComponent)oDoc).dispose();
oDoc = null;

Thanks to Mark Alexander Bain for source example here

Links

UNO (Universal Network Objects) Project

OpenOffice UNO SDK download

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s