Difference between revisions of "API/Tutorials/PDF export"

From Apache OpenOffice Wiki
< API‎ | Tutorials
Jump to: navigation, search
(PDF Export Configuration)
m
Line 118: Line 118:
 
''Minimum inclusive value'': 1. Represents lowest value that can be used. The lower the value, the less good is the compression quality and the bigger is be the file size.
 
''Minimum inclusive value'': 1. Represents lowest value that can be used. The lower the value, the less good is the compression quality and the bigger is be the file size.
  
''Minimum inclusive value'':100. Represents highest value that can be used. The higher the value, the better is the compression quality and the smaller is the file size.
+
''Maximum inclusive value'':100. Represents highest value that can be used. The higher the value, the better is the compression quality and the smaller is the file size.
 
| <center>long</center>
 
| <center>long</center>
 
| <center>90</center>
 
| <center>90</center>

Revision as of 07:42, 8 April 2008

PDF export is an important and useful feature of OpenOffice.org that can completely be automatized using OpenOffice.org API, quite every aspect of exporting to PDF in the graphical user interface is also available for programming: documents can be exported directly with default settings just passing the proper filter name and an URL, every option the user can set in the GUI can also be set programmatically in the filter options, also these settings are configurable via the API (they can be accessed, changed, or reset to their default values), and even the options dialog for exporting to PDF can be used through pure API calls.

This tutorial will show how to use OpenOffice.org API to export documents to PDF. The reader should have at least a basic knowledge about handling office documents (how to load and store a document), and should also know how to access OpenOffice.org configuration.

This tutorial also aims to provide a full up-to-date documentation about the PDF export filter options, as these specific properties are usually not documented and only available in the core OpenOffice.org source code (thus not accessible for developers aiming to work only with its API).

The sources for this tutorial can be found here. They are not intended to provide a ready-to-use PDF export application, but to give you a tool for doing your own experiments.


PDF Export basics

A document can be exported by saving it to a different location and using a special filter capable to write the document to the desired format. In the API, documents are storable through their interface com.sun.star.frame.XStorable, as discussed in detail in Developer's Guide - Office Development - Storing Documents.

For exporting, besides the location (in URL notation) where the exported document is to be stored, a filter name must be passed to XStorable.storeAsURL() and XStorable.storeToURL(). The property needed for this purpose is the string argument FilterName that takes the name of a filter already known by OpenOffice.org.

In the simplest case, all you need for exporting to PDF is the URL where you want to export the document and the filter name; this way, the document will be exported using the current PDF export settings (the ones used the last time, or the default values stipulated by the filter configuration, if this is first time).

The following code shows the basic procedure:

XComponent xComponent = null;
// create a new Writer document using a helper
xComponent = Helper.createNewDoc(m_xContext, "swriter");
 
// access its XTextDocument interface
XTextDocument xTextDocument = (XTextDocument) UnoRuntime.queryInterface(
        XTextDocument.class, xComponent);
 
// access the text body and set a string
XText xText = xTextDocument.getText();
xText.setString("Simple PDF export demo.");
 
// XStorable to store the document
XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
        XStorable.class, xComponent);
 
// XStorable.storeToURL() expects an URL telling where to store the document
// and an array of PropertyValue indicating how to store it
 
// URL = use helper method to get the home directory
String sURL = Helper.getHomeDir(m_xContext) + "/Simple_PDF_EXPORT_demo.pdf";
 
// Exporting to PDF consists of giving the proper
// filter name in the property "FilterName"
// With only this, the document will be exported
// using the existing PDF export settings
// (the one used the last time, or the default if the first time)
PropertyValue[] aMediaDescriptor = new PropertyValue[1];
aMediaDescriptor[0] = new PropertyValue();
aMediaDescriptor[0].Name = "FilterName";
aMediaDescriptor[0].Value = "writer_pdf_Export";
 
xStorable.storeToURL(sURL, aMediaDescriptor);


As the code shows, XStorable.storeToURL() expects an URL as first parameter, and an array of com.sun.star.beans.PropertyValue structs as second parameter, which implements the com.sun.star.document.MediaDescriptor service, consisting of property definitions. The media descriptor is used for loading/importing and saving/exporting documents, please refer to the Developer's Guide for a detailed explanation. In this case, it includes only the struct for the FilterName, indicating the name of the filter for exporting Writer documents to PDF.

You can fully customize the PDF export process by adding another PropertyValue struct to the MediaDescriptor array: FilterData. This parameter is used to pass properties specific for a special filter type. In the case of the PDF export filter, another array of PropertyValue structs is expected.

In the next section, we will describe the complete list of specific properties available at the present for the PDF export filter.


PDF Export filter data

The following tables contain all the properties available in the PDF export filter implementation in OpenOffice.org 2.4. You must be aware of the fact that they are implementation specific, so you may not find all of them in previous versions (nor expect that they remain the same in the future).

The tables follow the order of the PDF Export dialog tab pages, so that you can easily understand their meaning just comparing them with this dialog.

Notes:


General properties

Property Name
Description
Type
Default value
PageRange If this property is set, it indicates the range of pages to be printed.

If you want to print all the pages, leave this property unset.

If you want to export a selection, leave this property unset, setting only the property Selection.

string
empty
(all pages are printed)
Selection An any corresponding to the current selection in the document.
any
UseLosslessCompression Specifies if graphics are exported to PDF using a lossless compression eg. PNG or if they are compressed using the JPEG format.
boolean
false
Quality Specifies quality of the JPG export. A higher value results in higher quality and file.

Minimum inclusive value: 1. Represents lowest value that can be used. The lower the value, the less good is the compression quality and the bigger is be the file size.

Maximum inclusive value:100. Represents highest value that can be used. The higher the value, the better is the compression quality and the smaller is the file size.

long
90
ReduceImageResolution Specifies if the resolution of each image is reduced to the resolution specified by the property MaxImageResolution.
boolean
false
MaxImageResolution If the property ReduceImageResolution is set to true all images will be reduced to the given value in DPI.

Posible values:

  • 75
  • 150
  • 300
  • 600
  • 1200


long
300
SelectPdfVersion Specifies the version of PDF to emit.

Possible values:

  • 0 = PDF 1.4 (default selection).
  • 1 = PDF/A-1 (ISO 19005-1:2005)


long
0
UseTaggedPDF Determines if PDF are created by using special tags also known as Tagged PDF.
boolean
false
ExportFormFields Specifies whether form fields are exported as widgets or only their fixed print representation is exported.
boolean
true
FormsType Specifies the submitted format of a PDF form.

Possible values:

  • 0= Specifies that forms type FDF is used.
  • 1= Specifies that forms type PDF is used.
  • 2= Specifies that forms type HTML is used.
  • 3= Specifies that forms type XML is used.


long
0
ExportBookmarks Specifies if bookmarks are exported to PDF.
boolean
true
ExportNotes Specifies if notes are exported to PDF.
boolean
false
ExportNotesPages Specifies if notes pages are exported to PDF. (Notes pages are available in Impress documents only).
boolean
false
IsSkipEmptyPages Specifies that automatically inserted empty pages are suppressed. This option is active only if storing Writer documents.
boolean
false
IsAddStream Specifies that a stream is inserted to the PDF file which contains the original document for archiving purposes.
boolean
false


Initial view

Property Name
Description
Type
Default value
InitialView Specifies how the PDF document should be displayed when opened.

Possible values:

  • 0= Select the default viewer mode, neither outlines or thumbnails.
  • 1= The document is opened with outline pane opened
  • 2= The document is opened with thumbnail pane opened


long
0
InitialPage Specifies the page on which a PDF document should be opened in the viewer application.
long
1
Magnification Specifies the action to be performed when the PDF document is opened.

Possible values:

  • 0= Opens with default zoom magnification.
  • 1= Opens magnified to fit the entire page within the window.
  • 2= Opens magnified to fit the entire page width within the window.
  • 3= Opens magnified to fit the entire width of its boundig box within the window (cuts out margins).
  • 4= Opens with the zoom level specified in the Zoom property.


long
0
Zoom specifies the zoom level a PDF document is opened with. Only valid if "Magnification" is set to "4".
long
100
PageLayout Specifies the page layout to be used when the document is opened.

Possible values:

  • 0= Display the pages according to the reader configuration.
  • 1= Display one page at a time.
  • 2= Display the pages in one column.
  • 3= Display the pages in two columns odd pages on the right, to have the odd pages on the left the FirstPageOnLeft property should be used as well.


long
0
FirstPageOnLeft Used with the value 3 of the PageLayout property above, true if the first page (odd) should be on the left side of the screen.
boolean
false


User interface

Property Name
Description
Type
Default value
ResizeWindowToInitialPage Specifies that the PDF viewer window is opened full screen when the document is opened.
boolean
false
CenterWindow Specifies that the PDF viewer window is centered to the screen when the PDF document is opened.
boolean
false
OpenInFullScreenMode Specifies that the PDF viewer window is opened full screen, on top of all windows.
boolean
false
DisplayPDFDocumentTitle Specifies that the title of the document, if present in the document properties, is displayed in the PDF viewer window title bar.
boolean
true
HideViewerMenubar Specifies whether to hide the PDF viewer menubar when the document is active.
boolean
false
HideViewerToolbar Specifies whether to hide the PDF viewer toolbar when the document is active.
boolean
false
HideViewerWindowControls Specifies whether to hide the PDF viewer controls when the document is active.
boolean
false
UseTransitionEffects Specifies slide transitions are exported to PDF. This option is active only if storing Impress documents.
boolean
true
OpenBookmarkLevels Specifies how many bookmark levels should be opened in the reader application when the PDF gets opened.

Possible values:

  • -1: all bookmark levels are opened
  • 1 – 10: indicate a bookmark level (from 1 to 10)


long
-1


Links

Property Name
Description
Type
Default value
ExportBookmarksToPDFDestination Specifies that the bookmarks contained in the source OpenOffice.org file should be exported to the PDF file as Named Destination (see PDF 1.4 section 8.2.1).
boolean
false
ConvertOOoTargetToPDFTarget Specifies that the target documents with .od[tpgs] extension, will have that extension changed to .pdf when the link is exported to PDF. The source document remains untouched.
boolean
false
ExportLinksRelativeFsys Specifies that the file system related hyperlinks (file:// protocol) present in the document will be exported as relative to the source document location.
boolean
false
PDFViewSelection Specifies the way the exported PDF will be viewed (experienced) by the user.

Possible values:

  • 0 = Specifies that the PDF will be exported with all the links external to the document treated as URI. This is the Default
  • 1 = Specifies that the PDF will be exported in order to be viewed through a PDF reader application only. Valid only if not exporting to PDF/A-1 (e.g. SelectPdfVersion not set to 1).
  • 2 = Specifies that the PDF will be exported in order to be viewed through an Internet browser, using the PDF plug-in provided with it. The bookmark of the URI will be rendered compatible with the target bookmark generated with OOo PDF Export feature (see ExportBookmarksToPDFDestination, below).


long
0


Security

Property Name
Description
Type
Default value
EncryptFile If true, selects to encrypt the PDF document with a password. The PDF file can be opened only when the user enters the correct password.
boolean
false
DocumentOpenPassword This is the password that allows the user to open the PDF file is "EncryptFile" is set to true.
string
RestrictPermissions If true, selects to restrict some permissions. The permissions can be changed only when the user enters the correct password.
boolean
false
PermissionPassword This is the password that allows the user to access some permissions restricted if "RestrictPermissions" is set to true.
string
Printing Specifies what printing is allowed.

Possible values:

  • 0 = The document cannot be printed.
  • 1 = The document can be printed at low resolution only.
  • 2 = The document can be printed at maximum resolution.


long
2
Changes Specifies the change allowed to the document.

Possible values:

  • 0 = The document cannot be changed.
  • 1 = Inserting deleting and rotating pages is allowed.
  • 2 = Filling of form field is allowed.
  • 3 = Both filling of form field and commenting is allowed.
  • 4 = All the changes of the previous selections are permitted, with the only exclusion of page extraction (copy).


long
4
EnableCopyingOfContent Specifies that the pages and the document content can be extracted to be used in other documents (copy and paste).
boolean
true
EnableTextAccessForAccessibilityTools Specifies that the document content can be extracted to be used in accessibility applications.
boolean
true


Filter data demo

The following sample shows how to use the filer data to set some PDF export filter options.

We will create a new Writer document, write some text in it and draw two shapes. Then we will show how to export only these to shapes, setting also some view preferences (the PDF will open in full screen mode).

    // create a new Writer document using a helper
    xComponent = Helper.createNewDoc(m_xContext, "swriter");
 
    // access its XTextDocument interface
    XTextDocument xTextDocument = (XTextDocument) UnoRuntime.queryInterface(
            XTextDocument.class, xComponent);
 
    // draw a group of shapes
    // so that then we can select tehm and export ONLY them to PDF
    XShapeGroup xShapes = drawShapeGroup(xTextDocument);
 
    // XStorable to store the document
    XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
        XStorable.class, xComponent);
 
    // XStorable.storeToURL() expects an URL telling where to store the document
    // and an array of PropertyValue indicating how to store it
 
    // URL = use helper method to get the home directory
    String sURL = Helper.getHomeDir(m_xContext) + "/PDF_EXPORT_FilterData_demo.pdf";
 
    // Exporting to PDF consists of giving the proper
    // filter name in the property "FilterName"
    // With only this, the WHOLE document will be exported
    // using the existing PDF export settings
    // (the one used the last time, or the default if the first time)
    PropertyValue[] aMediaDescriptor = new PropertyValue[2];
    aMediaDescriptor[0] = new PropertyValue();
    aMediaDescriptor[0].Name = "FilterName";
    aMediaDescriptor[0].Value = "writer_pdf_Export";
 
    // By adding the "FilterData" we can control what is exported and how
    // For example, we will export ONLY the current selection
 
    PropertyValue[] aFilterData = new PropertyValue[3];
    aFilterData[0] = new PropertyValue();
    aFilterData[0].Name = "Selection";
    aFilterData[0].Value = select(xTextDocument, xShapes);
    // there was really no need to retrieve the selection
    // we could have used the XShapeGroup reference
 
    aFilterData[1] = new PropertyValue();
    aFilterData[1].Name = "DisplayPDFDocumentTitle";
    aFilterData[1].Value = Boolean.FALSE;
 
    aFilterData[2] = new PropertyValue();
    aFilterData[2].Name = "OpenInFullScreenMode";
    aFilterData[2].Value = Boolean.TRUE;
 
    aMediaDescriptor[1] = new PropertyValue();
    aMediaDescriptor[1].Name = "FilterData";
    aMediaDescriptor[1].Value = aFilterData;
 
    xStorable.storeToURL(sURL, aMediaDescriptor);            
 
    // open the PDF with your default PDF viewer
    // to check how it worked!
    Helper.executeSystemCommand(m_xContext, sURL);


To select an object is really simple: just get the current com.sun.star.frame.XController from the document com.sun.star.frame.XModel, query for the XController's com.sun.star.view.XSelectionSupplier,and select the object:

private Object select(XInterface xInterface, Object aAny){
        Object oSelection = null;
        try {
            XModel xModel = (XModel) UnoRuntime.queryInterface(
                    XModel.class, xInterface);
            if (xModel != null){
                XController xController = xModel.getCurrentController();
                XSelectionSupplier xSelectionSupplier = 
                        (XSelectionSupplier) UnoRuntime.queryInterface(
                        XSelectionSupplier.class, xController);
                xSelectionSupplier.select(aAny);
                // there is really no need to retrieve the selection
                oSelection = xSelectionSupplier.getSelection();
            }
        } finally {
            return oSelection;
        }
    }

PDF Export Configuration

The settings of PDF export dialog are stored in the OpenOffice.org registry every time the this dialog is used and the user confirms his/her choices. Not all properties passed to the PDF filter are stored in the registry (as it makes no sense, for example to make persistent the page range to be exported, or the passwords for protecting the document).

The following is a list of the properties not present in the OpenOffice.org registry, node path /org.openoffice.Office.Common/Filter/PDF/Export:

  1. DocumentOpenPassword
  2. EncryptFile
  3. PageRange
  4. PermissionPassword
  5. RestrictPermissions
  6. Selection

The following property is present, but deprecated (that's why we didn't include in the tables above):

  1. CompressMode [deprecated]


In the next sections, we will show how to access the configuration, change it, and restore it to its default values.


Accessing the configuration

import com.sun.star.beans.Property;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.XPropertySetInfo;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
 
 
public class PDFExportConfigAccess {
 
    private final XComponentContext m_xContext;
 
    public PDFExportConfigAccess(XComponentContext xContext){
        m_xContext = xContext;        
    }
 
    public static void main(String[] args) {
        try {
            // get the remote office component context
            XComponentContext xContext = Bootstrap.bootstrap();
 
            PDFExportConfigAccess demo = new PDFExportConfigAccess(xContext);
            demo.run();
 
        } catch (java.lang.Exception e){
            e.printStackTrace();
        }
        finally {
            System.exit( 0 );
        }
    }
 
    public void run(){
 
        Object oConfig = getPDFConfigAccess(m_xContext);
 
        if (oConfig == null ) {
            System.out.println("Impossible to access the PDF configuration");
            return;
        }
 
        XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(
                XPropertySet.class, oConfig);
 
        XPropertySetInfo xPropertySetInfo = xPropertySet.getPropertySetInfo();
 
        Property[] properties = xPropertySetInfo.getProperties();
 
        System.out.println("\nProperties and values\n");
 
        for (Property property : properties) {
            String sValue = "";
            try {
                Object aValue = xPropertySet.getPropertyValue( property.Name );
                sValue = String.valueOf( aValue );
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            System.out.println(property.Name + " =\t" + sValue);
        }
    }
 
    public static Object getPDFConfigAccess(XComponentContext xContext){
 
        Object oPDFExportConfig = null;
        try {
 
            XMultiComponentFactory xMCF = xContext.getServiceManager();
 
            Object oConfigProvider = xMCF.createInstanceWithContext(
                    "com.sun.star.configuration.ConfigurationProvider", xContext);
 
            XMultiServiceFactory oConfigProvMSF = 
                    (XMultiServiceFactory) UnoRuntime.queryInterface(
                XMultiServiceFactory.class, oConfigProvider);
 
            PropertyValue[] args = new PropertyValue[1];
 
            args[0] = new PropertyValue();
            args[0].Name = "nodepath";
            args[0].Value = "/org.openoffice.Office.Common/Filter/PDF/Export/";
 
            String sServiceName = "com.sun.star.configuration.ConfigurationAccess";
 
            oPDFExportConfig = oConfigProvMSF.createInstanceWithArguments(
                    sServiceName, args);
 
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return oPDFExportConfig;
        }
    }
 
 
}

Modifying the configuration

import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XChangesBatch;
 
 
public class PDFExportConfigUpdate {
 
    private final XComponentContext m_xContext;
 
    public PDFExportConfigUpdate(XComponentContext xContext){
        m_xContext = xContext;        
    }
 
    public static void main(String[] args) {
        try {
            // get the remote office component context
            XComponentContext xContext = Bootstrap.bootstrap();
 
            PDFExportConfigUpdate demo = new PDFExportConfigUpdate(xContext);
            demo.run();
 
        } catch (java.lang.Exception e){
            e.printStackTrace();
        }
        finally {
            System.exit( 0 );
        }
    }
 
    public void run() {
 
 
        Object oConfig = getPDFConfigUpdateAccess(m_xContext);
 
        if (oConfig == null) {
            System.out.println("Impossible to access the PDF configuration");
            return;
        }
 
        XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(
                XPropertySet.class, oConfig);
        try {
            // change some properties
 
            /**
             * The first property specifies that the resolution of each image
             * must be reduced to the resolution specified by the second property
             * The value is given in DPI.
             */
            xPropertySet.setPropertyValue("ReduceImageResolution", Boolean.TRUE);
            xPropertySet.setPropertyValue("MaxImageResolution", new Integer(600));
 
            /**
             * When exporting a document to PDF, the default is PDF 1.4
             * Since OOo 2.4 the PDF/A-1a is also supported.
             * PDF/A-1a is an ISO 19005-1:2005 International Standard.
             * 
             * NOTE that some other options WILL NOT be available if this format
             * is selected (UseTaggedPDF, ExportFormFileds, FormsType,
             * all security options)
             */
            xPropertySet.setPropertyValue("SelectPdfVersion", new Integer(1));
 
            /**
             * "Magnification" specifies the action to be performed 
             * when the PDF document is opened.
             * A value of 4 opens with the zoom level specified in the 
             * "Zoom" property.
             */
            xPropertySet.setPropertyValue("Magnification", new Integer(4));
            xPropertySet.setPropertyValue("Zoom", new Integer(60));
 
            //you must commit the changes, if not they will be lost
            XChangesBatch xChangesBatch = (XChangesBatch) UnoRuntime.queryInterface(
                    XChangesBatch.class, xPropertySet);
 
            xChangesBatch.commitChanges();
 
        } catch (UnknownPropertyException ex) {
            ex.printStackTrace();
        } catch (PropertyVetoException ex) {
            ex.printStackTrace();
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (WrappedTargetException ex) {
            ex.printStackTrace();
        }
    }
 
    public static Object getPDFConfigUpdateAccess(XComponentContext xContext){
 
        Object oPDFExportConfig = null;
        try {
 
            XMultiComponentFactory xMCF = xContext.getServiceManager();
 
            Object oConfigProvider = xMCF.createInstanceWithContext(
                    "com.sun.star.configuration.ConfigurationProvider", xContext);
 
            XMultiServiceFactory oConfigProvMSF = 
                    (XMultiServiceFactory) UnoRuntime.queryInterface(
                XMultiServiceFactory.class, oConfigProvider);
 
            PropertyValue[] args = new PropertyValue[1];
 
            args[0] = new PropertyValue();
            args[0].Name = "nodepath";
            args[0].Value = "/org.openoffice.Office.Common/Filter/PDF/Export/";
 
            // ConfigurationUpdateAccess instead of ConfigurationAccess
            String sServiceName = "com.sun.star.configuration.ConfigurationUpdateAccess";
 
            oPDFExportConfig = oConfigProvMSF.createInstanceWithArguments(
                    sServiceName, args);
 
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return oPDFExportConfig;
        }
    }
 
 
}

Resetting the configuration

import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XMultiPropertyStates;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XChangesBatch;
 
 
public class PDFExportConfigDefaulter {
 
    private final XComponentContext m_xContext;
 
    public PDFExportConfigDefaulter(XComponentContext xContext){
        m_xContext = xContext;        
    }
 
    public static void main(String[] args) {
        try {
            // get the remote office component context
            XComponentContext xContext = Bootstrap.bootstrap();
 
            PDFExportConfigDefaulter demo = new PDFExportConfigDefaulter(xContext);
            demo.run();
 
        } catch (java.lang.Exception e){
            e.printStackTrace();
        }
        finally {
            System.exit( 0 );
        }
    }
 
    public void run() {
 
        Object oConfig = getPDFConfigUpdateAccess(m_xContext);
 
        if (oConfig == null) {
            System.out.println("Impossible to access the PDF configuration");
            return;
        }
 
        XMultiPropertyStates xMultiPropertyStates = 
                (XMultiPropertyStates) UnoRuntime.queryInterface(
                XMultiPropertyStates.class, oConfig);
        try {
            // set all the properties to default values
            xMultiPropertyStates.setAllPropertiesToDefault();
 
            //you must commit the changes, if not they will be lost
            XChangesBatch xChangesBatch = (XChangesBatch) UnoRuntime.queryInterface(
                    XChangesBatch.class, xMultiPropertyStates);
 
            xChangesBatch.commitChanges();
 
        } catch (WrappedTargetException ex) {
            ex.printStackTrace();
        }
    }
 
    public static Object getPDFConfigUpdateAccess(XComponentContext xContext){
 
        Object oPDFExportConfig = null;
        try {
 
            XMultiComponentFactory xMCF = xContext.getServiceManager();
 
            Object oConfigProvider = xMCF.createInstanceWithContext(
                    "com.sun.star.configuration.ConfigurationProvider", xContext);
 
            XMultiServiceFactory oConfigProvMSF = 
                    (XMultiServiceFactory) UnoRuntime.queryInterface(
                XMultiServiceFactory.class, oConfigProvider);
 
            PropertyValue[] args = new PropertyValue[1];
 
            args[0] = new PropertyValue();
            args[0].Name = "nodepath";
            args[0].Value = "/org.openoffice.Office.Common/Filter/PDF/Export/";
 
            // ConfigurationUpdateAccess instead of ConfigurationAccess
            String sServiceName = "com.sun.star.configuration.ConfigurationUpdateAccess";
 
            oPDFExportConfig = oConfigProvMSF.createInstanceWithArguments(
                    sServiceName, args);
 
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return oPDFExportConfig;
        }
    }
 
}

All in one, with helpers

import com.sun.star.beans.Property;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XMultiPropertyStates;
import com.sun.star.beans.XPropertySet;
import com.sun.star.beans.XPropertySetInfo;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.XInterface;
import com.sun.star.util.XChangesBatch;
import java.util.ArrayList;
 
 
public class ConfigurationHelper {
 
    private final XComponentContext m_xContext;
 
    public ConfigurationHelper(XComponentContext xContext){
        m_xContext = xContext;        
    }
 
    public static void main(String[] args) {
        try {
            // get the remote office component context
            XComponentContext xContext = Bootstrap.bootstrap();
 
            ConfigurationHelper demo = new ConfigurationHelper(xContext);
            demo.run();
 
        } catch (java.lang.Exception e){
            e.printStackTrace();
        }
        finally {
            System.exit( 0 );
        }
    }
 
    public void run() throws Exception {
 
        String sNodepath = "/org.openoffice.Office.Common/Filter/PDF/Export/";
 
        // get a read-only view of the PDF Export configuration
        XInterface oConfig = getReadOnlyAccess(m_xContext, sNodepath);
 
        // access the view's XPropertySet
        XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(
                XPropertySet.class, oConfig);
 
        // print the current configuration values
        System.out.println("\n========   Current configuration values   ========");
        printPropertyValues(xPropertySet);
 
        // now get an updatable view of the PDF Export configuration
        oConfig = getUpdateAccess(m_xContext, sNodepath);
 
        // you must commit the changes, if not they will be lost
        // so query XChangesBatch
        XChangesBatch xChangesBatch = (XChangesBatch) UnoRuntime.queryInterface(
                XChangesBatch.class, oConfig);
 
        // access the view's XPropertySet
        xPropertySet = (XPropertySet) UnoRuntime.queryInterface(
                XPropertySet.class, oConfig);
 
        // change some properties
        xPropertySet.setPropertyValue("ReduceImageResolution", Boolean.TRUE);
        xPropertySet.setPropertyValue("MaxImageResolution", new Integer(600));
 
        xPropertySet.setPropertyValue("SelectPdfVersion", new Integer(1));
 
        xPropertySet.setPropertyValue("Magnification", new Integer(4));
        xPropertySet.setPropertyValue("Zoom", new Integer(60));
 
        // commit the changes
        xChangesBatch.commitChanges();
 
        // print the new configuration values
        System.out.println("\n========     New configuration values    ========");
        printPropertyValues(xPropertySet);
 
        // set all the properties to default values
        XMultiPropertyStates xMultiPropertyStates = 
                (XMultiPropertyStates) UnoRuntime.queryInterface(
                XMultiPropertyStates.class, oConfig);
        xMultiPropertyStates.setAllPropertiesToDefault();
 
        // commit the changes
        xChangesBatch.commitChanges();
 
        // print the defaulted configuration values
        System.out.println("\n========  Defaulted configuration values  ========");
        printPropertyValues(xPropertySet);
    }
 
    //*************************************************************************
    //*************************************************************************
 
    /**
     * 
     * 
     * @param xContext      com.sun.star.uno.XComponentContext
     * @param sNodePath     absolute configuration path that identifies 
     *                      a structural configuration item
     * @param bUpdateAccess     if true, you get a configuration view that
     *                          can be updatable; if false, then the view is read-only
     * @param aLocale       is a string (NOT a css.lang.Locale !)
     *                      You can pass the language ("de", "en"),
     *                      the language-country ("de-DE", "en-US"),
     *                      or "*" to access a view of the configuration
     *                      including all available locales in the office.
     * @return      A generic css.uno.XInterface, you must then query for the
     *              proper interface depending of configuration view you get
     *              (update/read-only, root/group/set, ...)
     * @throws com.sun.star.uno.Exception
     */
    public static XInterface getConfigurationAccess(
                                                    XComponentContext xContext,
                                                    String sNodePath,
                                                    boolean bUpdateAccess,
                                                    String aLocale)
            throws com.sun.star.uno.Exception {
 
        String sServiceName = bUpdateAccess
                ? "com.sun.star.configuration.ConfigurationUpdateAccess"
                : "com.sun.star.configuration.ConfigurationAccess";
 
        ArrayList<PropertyValue> args = new ArrayList<PropertyValue>();
 
        PropertyValue aNodePath = new PropertyValue();
        aNodePath.Name = "nodepath";
        aNodePath.Value = sNodePath;
        args.add(aNodePath);
 
        if ((aLocale != null) && (!aLocale.equals(""))) {
            PropertyValue aLocaleArgument = new PropertyValue();
            aLocaleArgument.Name = "Locale";
            aLocaleArgument.Value = aLocale;
            args.add(aLocaleArgument);
        }
 
        if (bUpdateAccess) {
            PropertyValue aModeArgument = new PropertyValue();
            aModeArgument.Name = "EnableAsync";
            aModeArgument.Value = Boolean.FALSE;
            args.add(aModeArgument);
        }
 
        XMultiComponentFactory xMCF = xContext.getServiceManager();
 
        XInterface oConfigProvider = (XInterface) xMCF.createInstanceWithContext(
                "com.sun.star.configuration.ConfigurationProvider", xContext);
        XMultiServiceFactory oConfigProvMSF = 
                (XMultiServiceFactory) UnoRuntime.queryInterface(
                XMultiServiceFactory.class, oConfigProvider);
 
        return (XInterface) oConfigProvMSF.createInstanceWithArguments(
                sServiceName, args.toArray(new PropertyValue[args.size()]));
    }
 
    /**
     * 
     * @param xContext      com.sun.star.uno.XComponentContext
     * @param sNodePath     absolute configuration path that identifies 
     *                      a structural configuration item
     * @return      A generic css.uno.XInterface, you must then query for the
     *              proper interface depending of configuration view you get
     * @throws com.sun.star.uno.Exception
     */
    public static XInterface getUpdateAccess(
                                                XComponentContext xContext, 
                                                String aNodePath) 
            throws com.sun.star.uno.Exception 
    {
        return getConfigurationAccess(xContext, aNodePath, true, null);
    }
 
    /**
     * 
     * @param xContext      com.sun.star.uno.XComponentContext
     * @param sNodePath     absolute configuration path that identifies 
     *                      a structural configuration item
     * @return      A generic css.uno.XInterface, you must then query for the
     *              proper interface depending of configuration view you get
     * @throws com.sun.star.uno.Exception
     */
    public static XInterface getReadOnlyAccess(
                                                XComponentContext xContext, 
                                                String aNodePath) 
        throws com.sun.star.uno.Exception 
    {
        return getConfigurationAccess(xContext, aNodePath, false, null);
    }
 
 
    //*************************************************************************
    //*************************************************************************
 
    public static void printPropertyValues(XPropertySet xPropertySet) 
    {        
        try {
            XPropertySetInfo xPropertySetInfo = xPropertySet.getPropertySetInfo();
 
            Property[] properties = xPropertySetInfo.getProperties();
 
            System.out.println("\nProperties and values\n");
 
            for (Property property : properties) {
                String sValue = "";
                try {
                    Object aValue = xPropertySet.getPropertyValue(property.Name);
                    sValue = String.valueOf(aValue);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                System.out.println(property.Name + " =\t" + sValue);
            }
 
        } catch (java.lang.Exception ex) {
            ex.printStackTrace();
        }
 
    }
 
}

PDF Export Dialog

How to use it from Java

import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertyAccess;
import com.sun.star.io.IOException;
import com.sun.star.uno.XComponentContext;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.document.XExporter;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.ui.dialogs.ExecutableDialogResults;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.CloseVetoException;
import com.sun.star.util.XCloseable;
import com.sun.star.util.XStringSubstitution;
 
public class PDFExportDialog {
 
    private final XComponentContext m_xContext;
 
    public PDFExportDialog(XComponentContext xContext){
        m_xContext = xContext;        
    }
 
    public static void main(String[] args) {
        try {
            // get the remote office component context
            XComponentContext xContext = Bootstrap.bootstrap();
 
            PDFExportDialog demo = new PDFExportDialog(xContext);
            demo.run();
 
        } catch (java.lang.Exception e){
            e.printStackTrace();
        }
        finally {
            System.exit( 0 );
        }
    }
 
    public void run() {
 
        XMultiComponentFactory xMCF = m_xContext.getServiceManager();
 
        Object oPDFDialog = null;
 
        try {
            oPDFDialog = xMCF.createInstanceWithContext(
                    "com.sun.star.document.PDFDialog", m_xContext);
        } catch (com.sun.star.uno.Exception ex) {
            ex.printStackTrace();
        }
 
        // get all interface references
        XExecutableDialog xExecutableDialog = 
                (XExecutableDialog) UnoRuntime.queryInterface(
                    XExecutableDialog.class, oPDFDialog);
 
        XExporter xExporter = (XExporter) UnoRuntime.queryInterface(
                XExporter.class, xExecutableDialog);
 
        XPropertyAccess xPropertyAccess = 
                (XPropertyAccess) UnoRuntime.queryInterface(
                    XPropertyAccess.class, xExporter);
 
        // check them all
        if (xExecutableDialog == null || 
                xExporter == null || xPropertyAccess == null) {
            System.out.println("something went wrong with the PDFDialog!");
            return;
        }
 
        XComponent xComponent = null;
        try {
            // change the following to test with different doc. types
            // but remember to change the filter name below
            xComponent = createNewDoc(m_xContext, "swriter");
 
            // set the source document
            xExporter.setSourceDocument(xComponent);
 
            // set the title
            xExecutableDialog.setTitle("Demo Export PDF Dialog OOo API");
 
            // execute the dialog
            int nResult = xExecutableDialog.execute();
 
            if (nResult != ExecutableDialogResults.OK) {
                System.out.println("you didn't press OK! so do nothing...");
                return;
            }
 
            // get the options the user has choosen
            PropertyValue[] aFilterData = null;
 
            PropertyValue[] aPropertyValues = xPropertyAccess.getPropertyValues();
            if (aPropertyValues.length > 0) {
                for (int i = 0; i < aPropertyValues.length; i++) {
                    PropertyValue propertyValue = aPropertyValues[i];
                    if (propertyValue.Name.equals("FilterData")) {
                        try {
                            aFilterData = (PropertyValue[]) AnyConverter.toObject(
                                    PropertyValue[].class, propertyValue.Value);
 
                        } catch (com.sun.star.lang.IllegalArgumentException ex) {
                            ex.printStackTrace();
                        }
                        break;
                    }
                }
            }
 
            if (aFilterData != null) {
                // print the properties and their values
                printPropertyValues(aFilterData);
 
                // finally export!                
                // location where to export the doc.
                String sURL = getHomeDir(m_xContext) + "/PDF_EXPORT_DIALOG_demo.pdf";                
                // choose the proper filter            
                String sFilter = "writer_pdf_Export";
 
                boolean bExport = doExport(xComponent, sURL, sFilter, aFilterData);
 
                System.out.println( (bExport) ? "\nExported!" : 
                    "\nCouldn't export the document!" );
            }
 
        } catch (java.lang.Exception ex) {
            ex.printStackTrace();
        } finally {
            if (xComponent != null) {
                try {
                    XCloseable xCloseable = (XCloseable) UnoRuntime.queryInterface(
                            XCloseable.class, xComponent);
                    xCloseable.close(true);
                } catch (CloseVetoException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
 
    private boolean doExport(
                                XComponent xComponent,
                                String aURL,
                                String sFilterName,
                                PropertyValue[] aFilterData)
    {
        XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
                XStorable.class, xComponent);
        if (xStorable == null) {
            return false;
        } else {
            try {
                PropertyValue[] aMediaDescriptor = new PropertyValue[2];
 
                aMediaDescriptor[0] = new PropertyValue();
                aMediaDescriptor[0].Name = "FilterName";
                aMediaDescriptor[0].Value = sFilterName;
 
                aMediaDescriptor[1] = new PropertyValue();
                aMediaDescriptor[1].Name = "FilterData";
                aMediaDescriptor[1].Value = aFilterData;
 
                xStorable.storeToURL(aURL, aFilterData);                
                return true;
 
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return false;
    }
 
    public static void printPropertyValues(PropertyValue[] aPropertyValues) 
    {
        System.out.println("\nProperties and values\n");
 
        for (PropertyValue property : aPropertyValues) {
            String sValue = "";
            try {
                sValue = String.valueOf(property.Value);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            System.out.println(property.Name + " = " + sValue);
        }
    }
 
 
    //*************************************************************************
 
    public static XComponent loadComponent(
                                    XComponentContext xContext, 
                                    String sURL, 
                                    PropertyValue[] aMediaDescriptor)
    {
        XComponent xComp = null;
        try {
            XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime.queryInterface(
                    XComponentLoader.class, 
                    xContext.getServiceManager().createInstanceWithContext(
                    "com.sun.star.frame.Desktop", xContext));
            xComp = xComponentLoader.loadComponentFromURL(
                    sURL, "_default", 0, aMediaDescriptor);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return xComp;
    }
 
    public static XComponent createNewDoc(
                                    XComponentContext xContext, 
                                    String sDocType, 
                                    PropertyValue[] aMediaDescriptor)
    {
        XComponent xComp = null;
        try {
            xComp = loadComponent(xContext, "private:factory/" + 
                    sDocType, aMediaDescriptor);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return xComp;
    }
 
    public static XComponent createNewDoc(
                                    XComponentContext xContext, 
                                    String sDocType)
    {
        XComponent xComp = null;
        try {
            xComp = createNewDoc(xContext, sDocType, new PropertyValue[0]);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return xComp;
    }
 
    public static XComponent createNewHiddenDoc(
                                    XComponentContext xContext, 
                                    String sDocType)
    {
        XComponent xComp = null;
        try {
            PropertyValue[] aMediaDescriptor = new PropertyValue[1];
            aMediaDescriptor[0] = new PropertyValue();
            aMediaDescriptor[0].Name = "Hidden";
            aMediaDescriptor[0].Value = Boolean.TRUE;
 
            xComp = createNewDoc(xContext, sDocType, aMediaDescriptor);
 
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return xComp;
    }
 
    //************************************************************************
    //*************************************************************************
 
    public static String getHomeDir(XComponentContext xContext) {
        return getPathSubstitution(xContext, "$(home)");
    }
 
    public static String getWorkDir(XComponentContext xContext) {
        return getPathSubstitution(xContext, "$(work)");
    }
 
    public static String getUserDir(XComponentContext xContext) {
        return getPathSubstitution(xContext, "$(user)");
    }
 
    /**
     *
     *      com.sun.star.util.PathSubstitution
     *
     *      $(inst)     Installation path of the Office. 
     *      $(prog)     Program path of the Office. 
     *      $(user)     The user installation directory. 
     *      $(work)     The work directory of the user. 
     *                      Under Windows this would be the "MyDocuments" subdirectory. 
     *                      Under Unix this would be the home-directory
     *      $(home)     The home directory of the user.
     *                      Under Unix this would be the home- directory. 
     *                      Under Windows this would be the "Documents and Settings\ " subdirectory.
     *      $(temp)     The current temporary directory. 
     *      $(path)     The value of PATH environment variable.
     *      $(lang)     The country code used by the Office, like 
     *                      01=english, 
     *                      49=german.
     *      $(langid)   The language code used by the Office, like 
     *                      0x0009=english, 
     *                      0x0409=english us.
     *      $(vlang)    The language used by the Office as a string. Like 
     *                      "german" for a german Office.
     *
     */    
    public static String getPathSubstitution(
            XComponentContext xContext, String aVariable)
    {
        String variableSubst = null;
        try {
            XStringSubstitution xStringSubstitution = getPathSubstitution(xContext);
            variableSubst = xStringSubstitution.getSubstituteVariableValue(aVariable);                
 
        } catch (com.sun.star.container.NoSuchElementException e) {
            e.printStackTrace();
        } catch (com.sun.star.uno.Exception ex) {
            ex.printStackTrace();
        } finally {
            return variableSubst;
        }        
    }
 
    public static String getPathSubstitution(
            XComponentContext xContext, String aText, boolean bSubstRequired)
    {
        String variableSubst = null;
        try {
            XStringSubstitution xStringSubstitution = getPathSubstitution(xContext);
            variableSubst = xStringSubstitution.substituteVariables(
                    aText, bSubstRequired);                
 
        } catch (com.sun.star.container.NoSuchElementException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return variableSubst;
        }        
    }
 
    public static XStringSubstitution getPathSubstitution(
                                                XComponentContext xContext)
    {
        XStringSubstitution xPathSubstitution = null;        
        XMultiComponentFactory xMCF = xContext.getServiceManager();        
        try {
            xPathSubstitution = (XStringSubstitution) UnoRuntime.queryInterface(
                    XStringSubstitution.class, 
                    xMCF.createInstanceWithContext(
                        "com.sun.star.util.PathSubstitution", xContext));            
        } catch (com.sun.star.uno.Exception ex) {
            ex.printStackTrace();
        } finally {
            return xPathSubstitution;
        }        
    }
 
}

How to use it from C++

ToDo


How to use it from OOo Basic

ToDo

Personal tools