From The Document Foundation Wiki
    < API‎ | Samples‎ | Java

    LibreOffice Application Environment

    The LibreOffice application environment is made up of the desktop environment and the framework API.

    If a document in LibreOffice is required, begin by getting a com.sun.star.frame.Desktop service from the service manager. The desktop handles all document components in LibreOffice, among other things.

    Office documents are often called components, because they support the <idl>com.sun.star.lang.XComponent</idl> interface. An <idls>com.sun.star.lang.XComponent</idls> is a UNO object that can be disposed explicitly and broadcast an event to other UNO objects when this happens.

    The process to work with LibreOffice document may start from:

    Getting a remote office component context

    The com.sun.star.comp.helper.Bootstrap.bootstrap() method initializes UNO and returns the remote component context of a runing LibreOffice process.

    com.sun.star.uno.XComponentContext xContext = null;
    xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();

    Getting the remote office service manager

    use the method <idlm>com.sun.star.lang.XComponentContext:getServiceManager</idlm>() from the component context to get the remote service manager from the LibreOffice process, which offers you access to the complete office functionality availale through the API.

    com.sun.star.lang.XMultiComponentFactory xMCF = xContext.getServiceManager();

    Creating the service of Desktop

    asked the service manager to create a <idl>com.sun.star.frame.Desktop</idl> using its factory method <idlm>com.sun.star.lang.XMultiComponentFactory:createInstanceWithContext</idlm>(). This method is defined to return a Java Object type.

    Object oDesktop = xMCF.createInstanceWithContext(
                    "com.sun.star.frame.Desktop", xContext);

    Querying for the interface <idls>com.sun.star.frame.XComponentLoader</idls> on the Desktop

    This is a simple interface to load components by an URL into a frame environment, it has one method <idlm>com.sun.star.frame.XComponentLoader:loadComponentFromURL</idlm>, which enable user to load the document as component by URL, and then the rest of manipulations. In Java or C++, you normally just cast an object before you access an interface it implements. When working with UNO objects, this is different: you must ask the UNO environment to get the appropriate reference for you whenever you want to access methods of an interface which you object supports, but your compiler does not yet know about, only then you can cast it safely. QueryInterface method is about safe casting of UNO types across process boundaries.

    com.sun.star.frame.XComponentLoader xCompLoader =
                             com.sun.star.frame.XComponentLoader.class, oDesktop);

    Now we are able to load a document and do the rest of tasks.

    SDK examples:


    – to load a LibreOffice Text Document

    The Desktop offers a facility to load components through its interface <idl>com.sun.star.frame.XComponentLoader</idl> as previously mentioned. The Desktop can load new and existing components from a URL. For this purpose it has a <idl>com.sun.star.frame.XComponentLoader</idl> interface that has one single method to load and instantiate components from a URL into a frame:

    com::sun::star::lang::XComponent loadComponentFromURL ( 
                      [in] string aURL,
                      [in] string aTargetFrameName,
                      [in] long nSearchFlags,
                      [in] sequence < com::sun::star::beans::PropertyValue aArgs > )

    The URL can be a file: URL, a http: URL, an ftp: URL or a private: URL. Look up the correct URL format in the load URL box in the function bar of LibreOffice. For new writer documents, a special URL scheme has to be used. The scheme is "private:", followed by "factory" as hostname. The resource is "swriter" for LibreOffice writer documents. For a new writer document, use "private:factory/swriter".

    A call to <idlm>com.sun.star.frame.XComponentLoader:loadComponentFromURL</idlm>() receives a sequence of <idl>com.sun.star.beans.PropertyValue</idl> structs as a parameter, which implements the <idl>com.sun.star.document.MediaDescriptor</idl> service, consisting of property definitions. It describes where a resource or medium should be loaded from and how this should be done.

    The media descriptor is also used for saving a document to a location using the interface <idl>com.sun.star.frame.XStorable</idl>. It transports the "where to" and the "how" of the storing procedure. You may look at SDK examples – DocumentSaver.

    Some properties are used for loading and saving while others apply to one or the other. If a media descriptor is used, only a few of the members are specified. The others assume default values. Strings default to empty strings in general and interface references default to empty references. For all other properties, the default values are specified in the description column of the <idl>com.sun.star.document.MediaDescriptor</idl>.

    Some properties are tagged deprecated. There are old implementations that still use these properties. They are supported, but are discouraged to use them. Use the new property that can be found in the description column of the deprecated property.

    To develop a UNO component that uses the media descriptor, note that all the properties are under control of the framework API. Never create your own property names for the media descriptor, or name clashes may be induced if the framework defines a property that uses the same name. Instead, use the ComponentData property to transport document specific information. ComponentData is specified to be an any, therefore it can be a sequence of property values by itself. If you do use it. make an appropriate specification available to users of your component.

    DocumentSaver and DocumentConverter

    Saving a document

    These Examples show the usage of the same interface – com.sun.star.frame.Xstorable and how the PropertyValue stetting effects the result, therefore turn to be a document converter.

    Object oDocToStore = xCompLoader.loadComponentFromURL(
                    sLoadUrl.toString(), "_blank", 0, propertyValue );
                com.sun.star.frame.XStorable xStorable =
                        com.sun.star.frame.XStorable.class, oDocToStore );
                propertyValue = new com.sun.star.beans.PropertyValue[ 2 ];
                propertyValue[0] = new com.sun.star.beans.PropertyValue();
                propertyValue[0].Name = "Overwrite";
                propertyValue[0].Value = new Boolean(true);
                propertyValue[1] = new com.sun.star.beans.PropertyValue();
                propertyValue[1].Name = "FilterName";
                propertyValue[1].Value = "StarOffice XML (Writer)";
                xStorable.storeAsURL( sSaveUrl.toString(), propertyValue );

    By querying XStorable interface from opened document/component, you will be able to call its store, storeAsURL or storeToURL methods to perform saving task. These methods are used in different situations.

    Methods Description
    store stores the data to the URL from which it was loaded. Only objects which know their locations can be stored.
    storeAsURL stores the object's persistent data to a URL and makes this URL the new location of the object. This is the normal behavior for UI's "save-as" feature.
    storeToURL stores the object's persistent data to a URL and continues to be a representation of the old URL. This is the normal behavior for UI's export feature. This method accepts all kinds of export filters, not only combined import/export filters because it implements an exporting capability, not a persistence capability.

    MediaDescriptor and Filters for exporting

    the parameters for saving, in the examples referred to the variable - <idl>com.sun.star.beans.PropertyValue</idl> propertyValue, please see <idls>com.sun.star.document.MediaDescriptor</idls> for further details. One of MediaDescriptor properties should be mentioned here, is <idlm>com.sun.star.document.MediaDescriptor:FilterName</idlm>, which was used in both examples. The filter name is internal filter name, that should be used for loading or storing the component. Names must match the names of the TypeDetection configuration, invalid names are ignored. For a list of filter name supported, you may get it from this examples a macro written in LibreOffice Basic.

    Closing a document

    Sometimes it is necessary to exercise more control over the closing process, therefore a new, optional interface <idl>com.sun.star.util.XCloseable</idl> has been introduced which is supported in versions beyond 641. If the object you are referencing is a <idls>com.sun.star.util.XCloseable</idls>, register it as a <idl>com.sun.star.util.XCloseListener</idl> and throw a <idl>com.sun.star.util.CloseVetoException</idl> when prompted to close. Since XCloseable is specified as an optional interface for frames and models, do not assume that this interface is supported. It is possible that the code runs with a LibreOffice version where frames and models do not implement XCloseable. Therefore ,be prepared for the case when you receive null when you try to query XCloseable. The following code ensure the document/component is closed/disposed.

    // Closing the converted document. Use XCloseable.close if the
                        // interface is supported, otherwise use XComponent.dispose
                        com.sun.star.util.XCloseable xCloseable =
                                com.sun.star.util.XCloseable.class, xStorable);
                        if ( xCloseable != null ) {
                        } else {
                            com.sun.star.lang.XComponent xComp =
                                    com.sun.star.lang.XComponent.class, xStorable);

    More details about <idls>com.sun.star.util.XCloseable</idls> can be found in the IDL type reference.


    Based on previous knowledges of this text, DocumentPrinter example introduces com.sun.star.view.XPrintable interface for the printing functionality of LibreOffice

    // Querying for the interface XPrintable on the loaded document
                com.sun.star.view.XPrintable xPrintable =
                        com.sun.star.view.XPrintable.class, xComp);

    To print a document, considering 2 factors:

    Where to print? -> the name of favoured printer
    What to print? -> which pages of this document need to be print, the page numbers

    It's done through <idlml>XPrintable:setPrinter</idlml>(...) and <idlml>com.sun.star.view.XPrintable:print</idlml>(...) methods. The parameters , printer name and pages numbers are sequence of <idl>com.sun.star.beans.PropertyValue</idl> structs specified in <idl>com.sun.star.document.MediaDescriptor</idl>.

    // Setting the property "Name" for the favoured printer (name of
                // IP address)
                com.sun.star.beans.PropertyValue propertyValue[] =
                    new com.sun.star.beans.PropertyValue[1];
                propertyValue[0] = new com.sun.star.beans.PropertyValue();
                propertyValue[0].Name = "Name";
                propertyValue[0].Value = args[ 0 ];
                // Setting the name of the printer
                xPrintable.setPrinter( propertyValue );
                // Setting the property "Pages" so that only the desired pages
                // will be printed.
                propertyValue[0] = new com.sun.star.beans.PropertyValue();
                propertyValue[0].Name = "Pages";
                propertyValue[0].Value = args[ 2 ];
                // Printing the loaded document
                xPrintable.print( propertyValue );

    Example project download


    Apache Feather Logo.svg

    This work is licensed under the Apache License version 2.0