API/Samples/Java/Office/DocumentHandling

From Apache OpenOffice Wiki
< API‎ | Samples‎ | Java
Jump to: navigation, search



OpenOffice.org Application Environment

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

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

Office documents are often called components, because they support the com.sun.star.lang.XComponent interface. An XComponent 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 OpenOffice.org 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 OpenOffice.org 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 getServiceManager() from the component context to get the remote service manager from the OpenOffice.org 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 com.sun.star.frame.Desktop using its factory method createInstanceWithContext(). This method is defined to return a Java Object type.

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

Querying for the interface XComponentLoader on the Desktop

This is a simple interface to load components by an URL into a frame environment, it has one method loadComponentFromURL, 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)UnoRuntime.queryInterface(
                         com.sun.star.frame.XComponentLoader.class, oDesktop);

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

SDK examples:

DocumentLoder

– to load a OpenOffice.org Text Document

The Desktop offers a facility to load components through its interface com.sun.star.frame.XComponentLoader as previously mentioned. The Desktop can load new and existing components from a URL. For this purpose it has a com.sun.star.frame.XComponentLoader 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 OpenOffice.org. 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 OpenOffice.org writer documents. For a new writer document, use "private:factory/swriter".

A call to loadComponentFromURL() receives a sequence of com.sun.star.beans.PropertyValue structs as a parameter, which implements the com.sun.star.document.MediaDescriptor 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 com.sun.star.frame.XStorable. 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 com.sun.star.document.MediaDescriptor.

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)UnoRuntime.queryInterface(
                    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 - com.sun.star.beans.PropertyValue propertyValue, please see MediaDescriptor for further details. One of MediaDescriptor properties should be mentioned here, is FilterName, 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 OpenOffice.org Basic.

Closing a document

Sometimes it is necessary to exercise more control over the closing process, therefore a new, optional interface com.sun.star.util.XCloseable has been introduced which is supported in versions beyond 641. If the object you are referencing is a XCloseable, register it as a com.sun.star.util.XCloseListener and throw a com.sun.star.util.CloseVetoException 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 OpenOffice.org 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)UnoRuntime.queryInterface(
                            com.sun.star.util.XCloseable.class, xStorable);
 
                    if ( xCloseable != null ) {
                        xCloseable.close(false);
                    } else {
                        com.sun.star.lang.XComponent xComp =
                            (com.sun.star.lang.XComponent)UnoRuntime.queryInterface(
                                com.sun.star.lang.XComponent.class, xStorable);
 
                        xComp.dispose();


More details about XCloseable can be found in the IDL type reference.

DocumentPrinter

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

 // Querying for the interface XPrintable on the loaded document
            com.sun.star.view.XPrintable xPrintable =
                (com.sun.star.view.XPrintable)UnoRuntime.queryInterface(
                    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 com.sun.star.beans.PropertyValue structs specified in com.sun.star.document.MediaDescriptor.

// 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

File:DocumentHandling.zip

Personal tools