Már született cikk az oldalon a WORD 2013 kezeléséről, most az OpenOffice, illetve a LibreOffice rejtelmeibe tekintünk be egy kicsit. Megvizsgáljuk mi szükséges ahhoz, hogy egy ODT kiterjesztésű fájlt megnyissunk egy C# programból.
Először is telepítenünk kell a LibreOffice SDK -t. Létre kell hoznunk egy új projektet és meg kell adnunk a szükséges referenciákat:
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.util;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.sheet;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.table;
using unoidl.com.sun.star.text;
#region Fields
private static unoidl.com.sun.star.uno.XComponentContext localContext;
private static unoidl.com.sun.star.lang.XMultiServiceFactory multiServiceFactory;
private static XComponentLoader componentLoader;
private static XComponent xComponent;
private static XTextDocument textDocument;
// A kísérletezést nem muszáj túlboncsolítani, itt is megadhatunk egy fájlnevet.
private static string FileName = @"c:\Users\X\tmp\mintafile.odt";
#endregion
///
/// Inicializálja a z OpenOffice-t, illetve a LibreOffice-t/// private static void LibreStart()
{
// A bootstrap metódus hívása
localContext = uno.util.Bootstrap.bootstrap();
// Service manager - MultiServiceFactory típus
multiServiceFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory) localContext.getServiceManager();
// Új Desktop példány létrehozása
componentLoader =(XComponentLoader) multiServiceFactory.createInstance("com.sun.star.frame.Desktop");}
private static void Show(string filename, bool rdonly)
{
uno.Any a = new uno.Any(rdonly.GetType(), rdonly);
PropertyValue pv = new PropertyValue();
pv.Name = "ReadOnly";
pv.Value = (uno.Any)a;
PropertyValue[] properties = new PropertyValue[1];
properties[0] = pv;
xComponent = componentLoader.loadComponentFromURL(
PathConverter(filename), "_blank", 0, properties);
textDocument = (XTextDocument)xComponent;
}
A PathConverter függvény nem tesz mást, mint kicseréli a backslash karaktereket "/"-re és az útvonal elé biggyeszti a "file:///" sztringet. Nem tartottam szükségesnek, hogy kifejtsem, de ha valakit érdekel szívesen ismertetem a kódját.
Végül az xComponent.dispose(); segítségével felszabadíthatjuk a memóriát, de vigyázat, bezárja az általunk megnyitott dokumentumokat is!
Sok sikert!
Sziklai Frigyes
szfrigyes@gmail.com