OpenOffice.org Forum at OOoForum.orgThe OpenOffice.org Forum
 
 [Home]   [FAQ]   [Search]   [Memberlist]   [Usergroups]   [Register
 [Profile]   [Log in to check your private messages]   [Log in

Example Java create, populate, save template-based document
Goto page 1, 2  Next
 
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets
View previous topic :: View next topic  
Author Message
robg123
General User
General User


Joined: 28 Aug 2007
Posts: 22

PostPosted: Tue Aug 28, 2007 8:46 pm    Post subject: Example Java create, populate, save template-based document Reply with quote

Folks:

This example Java application shows you how to do the following in Java:
    Create an OpenOffice Writer document and save it in PDF or MS Word-compatible format.
    Optionally use a template document from which the new document will be initially copied.
    Insert text, charts, and images into template-defined bookmarked text fields, or into the main document body.
    Control whether the user can edit the displayed window.
    Control document window visibility.
    Add document window visibility and dispose listeners.

There may be more efficient techniques out there for performing some of these functions (and please let me know about them!), but the techniques shown in this demo application are being used successfully in an operational system I developed for a customer.

I hope this code will save you some development time and keep you from re-inventing the wheel.

See also the snippet "Example Java create a chart for insertion into a Writer document" (http://www.oooforum.org/forum/viewtopic.phtml?t=61911).

Code:

/**
 * File: WriterDoc.java
 *
 * Initial version: Aug 28, 2007
 *
 * Modifications:
 */
package office;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import office.Chart.ChartInsertionModeEnum;

import com.sun.star.awt.XWindow;
import com.sun.star.awt.XWindowListener;
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.comp.helper.BootstrapException;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XNameAccess;
import com.sun.star.container.XNameContainer;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XController;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.EventObject;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XEventListener;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.style.XStyleFamiliesSupplier;
import com.sun.star.text.XBookmarksSupplier;
import com.sun.star.text.XText;
import com.sun.star.text.XTextContent;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XTextFieldsSupplier;
import com.sun.star.text.XTextRange;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.xml.dom.XDocument;

/**
 * An example of creating an OpenOffice Writer document.  This class
 * demonstrates techniques to do the following:
 * <ul>
 * <li>Create an OpenOffice Writer document and save it in PDF or an
 *     MS Word-compatible format.
 * <li>Optionally use a template document from which the new document
 *     will be initially copied.
 * <li>Insert text, charts, and images into template-defined bookmarked
 *     text fields, or into the main document body.
 * <li>Control whether the user can edit the displayed window.
 * <li>Control document window visibility.
 * <li>Add document window visibility and dispose listeners.
 * </ul>
 * <p>
 * <b>Implementation Suggestions:</b>
 * <ul>
 * <li>The lengthy code sequences in this demo class should be logically
 *      abstracted into additional methods and classes.
 * <li>Methods should be included to let callers add window listeners
 *     (examples of adding listeners are within the <code>createDoc</code>
 *     method).
 * <li>The enumeration classes <code>DocumentFormatEnum</code> and
 *     <code>TextInsertionModeEnum</code> should be removed into their
 *     own files.
 * </ul>
 * <p>
 * @author rdg
 */
public class WriterDoc {

    private static XComponentContext context;

    /** Constructor. */
    public WriterDoc() { }

    /**
     * Create an OpenOffice Writer document and make it visible on the screen.
     * <p>
     * @return
     *     The 'handle' to the document.
     * @param docTitle
     *     The title of the document.  This will show up in the title
     *     bar of the document window.
     * @param templateFile
     *     The absolute path of a template file.  If not null, the newly
     *     created file will initially be an exact duplicate of this file.
     *     Typically, the template file contains bookmarks where this
     *     application can insert text, images, charts, etc.  (The template
     *     can be created using OpenOffice Writer).  If this parameter is
     *     null, the new document will be blank.
     * @param isUserEditable
     *     True = allow user to manipulate/edit the Writer document window.
     *     False = make the Writer document window uneditable.
     */
    public XComponent createDoc(
            String docTitle,
            String templateFile,
            boolean isUserEditable) throws java.lang.Exception {

        XComponent document = null;

        ////////////////////////////////////////////////////////////////////
        // Create the document.
        ////////////////////////////////////////////////////////////////////

        System.out.println(
                "WriterDoc: Start up or connect to the remote service manager.");

        // Get remote service manager.  We only need one instance regardless
        // of the number of documents we create.
        if (context == null) {
            try {
                context = Bootstrap.bootstrap();
            } catch (BootstrapException e) {
                throw new java.lang.Exception(e);
            }
        }
        XMultiComponentFactory serviceManager = context.getServiceManager();

        // Retrieve the Desktop object and get its XComponentLoader.
        Object desktop = serviceManager.createInstanceWithContext(
                "com.sun.star.frame.Desktop", context);
        XComponentLoader loader = (XComponentLoader) UnoRuntime.queryInterface(
                XComponentLoader.class, desktop);

        // Define general document properties (see
        // com.sun.star.document.MediaDescriptor for the possibilities).
        ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
        PropertyValue p = null;
        if (templateFile != null) {
            // Enable the use of a template document.
            p = new PropertyValue();
            p.Name = "AsTemplate";
            p.Value = new Boolean (true);
            props.add(p);
        }
        if ((docTitle != null) && (docTitle.length() > 0)) {
            p = new PropertyValue();
            p.Name = "DocumentTitle";
            p.Value = docTitle;
            props.add(p);
        }
        // Make the document initially invisible so the user does not
        // have to watch it being built.
        p = new PropertyValue();
        p.Name = "Hidden";
        p.Value = new Boolean(true);
        props.add(p);

        PropertyValue[] properties = new PropertyValue[props.size()];
        props.toArray(properties);

        // Create the document
        // (see com.sun.star.frame.XComponentLoader for argument details).

        document = null;

        if (templateFile != null) {
            // Create a new document that is a duplicate of the template.

            System.out.println(
                    "WriterDoc: Create the document '" + docTitle +
                    "' based on template " + templateFile + ".");

            String templateFileURL = filePathToURL(templateFile);
            document = loader.loadComponentFromURL(
                    templateFileURL,    // URL of templateFile.
                    "_blank",           // Target frame name (_blank creates new frame).
                    0,                  // Search flags.
                    properties);        // Document attributes.
        }
        else {
            // Create an empty document.

            System.out.println(
                    "WriterDoc: Create the empty document '" + docTitle + "'.");

            String docType = "swriter";
            String newDocURL = "private:factory/" + docType;
            document = loader.loadComponentFromURL (
                    newDocURL,          // URL for creating a new document.
                    "_blank",           // Target frame name (_blank creates a new frame).
                    0,                  // Search flags.
                    properties);        // Document properties.
        }

        // Get the document window and frame.

        XModel model = (XModel) UnoRuntime.queryInterface(
                XModel.class, document);
        XController c = model.getCurrentController();
        XFrame frame = c.getFrame();
        XWindow window = frame.getContainerWindow();

        ////////////////////////////////////////////////////////////////////
        // Add document window listeners.
        ////////////////////////////////////////////////////////////////////

        System.out.println("WriterDoc: Add window listeners.");

        // Example of adding a document displose listener so the application
        // can know if the user manually exits the Writer window.

        document.addEventListener(new XEventListener() {
            public void disposing(EventObject e) {
                System.out.println(
                        "WriterDoc (Event Listener): The document window is closing.");
            }
        });

        // Example of adding a window listener so the application can know
        // when the document becomes initially visible (in the case of this
        // implementation, we will manually set it visible below after we
        // finish building it).

        window.addWindowListener(new XWindowListener() {
            public void windowShown(com.sun.star.lang.EventObject e) {
                System.out.println(
                        "WriterDoc (Window listener): The document window has become visible.");
            }
            public void windowHidden(com.sun.star.lang.EventObject e) { }
            public void disposing(com.sun.star.lang.EventObject e) { }
            public void windowResized(com.sun.star.awt.WindowEvent e) { }
            public void windowMoved(com.sun.star.awt.WindowEvent e) { }
        });

        ////////////////////////////////////////////////////////////////////
        // Control whether user can edit the document.
        ////////////////////////////////////////////////////////////////////

        if (! isUserEditable) {
            window.setEnable(isUserEditable);
        }

        ////////////////////////////////////////////////////////////////////
        // Get the document's fields and bookmarks if any.
        ////////////////////////////////////////////////////////////////////

        System.out.println("WriterDoc: Get document fields/bookmarks if any.");

        // Fetch field and style information.
        // NOTE: I have not found a use for these yet.

        XTextFieldsSupplier fieldSupplier = (XTextFieldsSupplier)
            UnoRuntime.queryInterface(XTextFieldsSupplier.class, document);
        XStyleFamiliesSupplier styleFamiliesSupplier = (XStyleFamiliesSupplier)
            UnoRuntime.queryInterface(XStyleFamiliesSupplier.class, document);

        // Get the document's bookmark name supplier.

        XBookmarksSupplier bookmarksSupplier = (XBookmarksSupplier)
        UnoRuntime.queryInterface(XBookmarksSupplier.class, document);

        ////////////////////////////////////////////////////////////////////
        // Example of inserting text into a field bookmarked in the template
        ////////////////////////////////////////////////////////////////////

        XTextRange textRange = null;

        // XText is the main interface to a distinct text unit, for
        // example, the main text of a document, the text for headers
        // and footers, or a single cell of a table.  It's
        // insertTextContent method allows insertion of a text table,
        // text frame, or text field.
        XText textContent = null;

        // XTextCursor provides methods to move the insertion/extraction
        // cursor within an XText text unit.  In this case, we're
        // defaulting the cursor to the beginning of the text unit.
        XTextCursor textCursor = null;

        // The name of the bookmark to insert the text into.
        String bookmarkName = "Bookmark1";

        if (templateFile != null) {
            System.out.println(
                    "WriterDoc: Insert text into the bookmarked text field named '" +
                    bookmarkName + "'.");
            // Get the XTextRange associated with the specified bookmark.
            textRange = getBookmarkTextRange(bookmarksSupplier, bookmarkName);
            textContent = textRange.getText();
            // Create a text cursor then navigate to the text range.
            textCursor = textContent.createTextCursor();
            textCursor.gotoRange(textRange, false);
        }
        else {
            System.out.println(
            "WriterDoc: Insert text into the document body.");
            // Get the XTextRange associated with the main document body.
            XTextDocument textDocument = (XTextDocument) UnoRuntime.queryInterface(
                    XTextDocument.class, model);
            textContent = textDocument.getText();
            textCursor = textContent.createTextCursor();
        }

        // How we will insert the text.
        TextInsertionModeEnum textInsertMode = TextInsertionModeEnum.REPLACE_ALL;

        // The text we will insert.
        String textToInsert = "Inserted " + bookmarkName + " text";
        if (textInsertMode == TextInsertionModeEnum.ADD_SENTENCE) {
            textToInsert = "  " + textToInsert;
        }
        else if (textInsertMode == TextInsertionModeEnum.ADD_PARAGRAPH) {
            textToInsert = "\r\n" + textToInsert;
        }

        // Insert the given text at the bookmark position according to
        // the desired insertion mode.
        if (textInsertMode == TextInsertionModeEnum.REPLACE_ALL) {
            textCursor.setString(textToInsert);
        }
        else {
            String existingText = textCursor.getString();
            if (existingText.length() > 0) {
                textCursor.goRight((short) 0, false);
            }
            textCursor.setString(textToInsert);
        }

        // Move to the end of the text we just inserted.
        textCursor.goRight((short) textToInsert.length(), false);

        // NOTE: If the inserted text needs to have a particular font
        // and/or color, then do the following in the above code:
        //
        //    1. Before calling setString, save the XTextCursor's property set.
        //    2. Modify the XTextCursor's property set as desired.  Following
        //       are the names of properties typically modified for color and
        //       font: CharColor, CharFontName, CharFontFamily, CharFontPitch,
        //       CharFontPosture, CharFontWeight, CharHeight.
        //    3. After calling setString and moving the cursor to the end of
        //       the inserted text, restore the XTextCursor's original properties.

        ////////////////////////////////////////////////////////////////////
        // Example of inserting a chart into the document.
        ////////////////////////////////////////////////////////////////////

        ChartInsertionModeEnum chartInsertMode = null;
        bookmarkName = "Bookmark2";

        if (templateFile != null) {
            System.out.println(
                    "WriterDoc: Insert a chart into the bookmarked text field named '" +
                    bookmarkName + "'.");
            chartInsertMode = ChartInsertionModeEnum.INSERT_IN_TEXT_FIELD;
            // Get the XTextRange associated with the specified bookmark.
            textRange = getBookmarkTextRange(bookmarksSupplier, bookmarkName);
            textContent = textRange.getText();
            // Create a text cursor then navigate to the text range into which
            // we are inserting the chart.
            textCursor = textContent.createTextCursor();
            textCursor.gotoRange(textRange, false);
        }
        else {
            System.out.println(
                "WriterDoc: Insert a chart into the document body.");
            chartInsertMode = ChartInsertionModeEnum.INSERT_IN_TEXT_BODY;
            // Get the XTextRange associated with the document body.
            XTextDocument textDocument = (XTextDocument) UnoRuntime.queryInterface(
                    XTextDocument.class, model);
            textContent = textDocument.getText();
            textCursor = textContent.createTextCursor();
        }

        // Note: the Chart.createChart method creates the document AND inserts it.

        System.out.println(
                "WriterDoc: Create and insert a chart into a bookmarked field.");

        Chart chart = new Chart();
        chart.createChart(
                document,
                textContent,
                textCursor,
                Chart.ChartStyleEnum.BAR_DIAGRAM,
                chartInsertMode);

        ////////////////////////////////////////////////////////////////////
        // Example of inserting an image from a file into the document.
        ////////////////////////////////////////////////////////////////////

        String imageFile =
            "C:/Documents and Settings/Rob/My Documents/EclipseProjects/OpenOffice/SunMicrosystems_109_70.jpg";
        String imageFileURL = filePathToURL(imageFile);
        ImageInsertionModeEnum imageInsertMode = null;
        bookmarkName = "Bookmark3";

        if (templateFile != null) {
            System.out.println(
                    "WriterDoc: Insert an image into the bookmarked text field named '" +
                    bookmarkName + "'.");
            imageInsertMode = ImageInsertionModeEnum.INSERT_IN_TEXT_FIELD;
            // Get the XTextRange associated with the specified bookmark.
            textRange = getBookmarkTextRange(bookmarksSupplier, bookmarkName);
            textContent = textRange.getText();
            // Create a text cursor then navigate to the text range.
            textCursor = textContent.createTextCursor();
            textCursor.gotoRange(textRange, false);
        }
        else {
            System.out.println(
            "WriterDoc: Insert an image from a file into the document body.");
            imageInsertMode = ImageInsertionModeEnum.INSERT_IN_TEXT_BODY;
            // Get the XTextRange associated with the document body.
            XTextDocument textDocument = (XTextDocument) UnoRuntime.queryInterface(
                    XTextDocument.class, model);
            textContent = textDocument.getText();
            textCursor = textContent.createTextCursor();
        }

        // Create an internal bit map.
        XMultiServiceFactory docServices = (XMultiServiceFactory)
            UnoRuntime.queryInterface(XMultiServiceFactory.class, model);
        XNameContainer bitMap = (XNameContainer) UnoRuntime.queryInterface(
                XNameContainer.class, docServices.createInstance(
                        "com.sun.star.drawing.BitmapTable"));

        // Copy the image from the file into the document, then create an internal
        // URL that points to it.
        bitMap.insertByName("MyTempID", imageFileURL);
        String internalURL = (String) bitMap.getByName("MyTempID");

        // Create an object in which to store the image, and get its properties.
        XTextContent imageObject = (XTextContent) UnoRuntime.queryInterface(
                XTextContent.class, docServices.createInstance(
                        "com.sun.star.text.TextGraphicObject"));
        XPropertySet pSet = (XPropertySet) UnoRuntime.queryInterface(
                XPropertySet.class, imageObject);

        // Link the internal image to the TextGraphicObject and insert it
        // at the cursor position.
        pSet.setPropertyValue(
                "AnchorType", com.sun.star.text.TextContentAnchorType.AS_CHARACTER);
        pSet.setPropertyValue(
                "GraphicURL", internalURL);
        // Note: If Width and Height are not given, the image's normal size
        // will be used.  Width and Height units are 100ths of a millimeter.
        pSet.setPropertyValue(
                "Width", new Integer(2600));
        pSet.setPropertyValue(
                "Height", new Integer(2000));

        if ((imageInsertMode == ImageInsertionModeEnum.INSERT_IN_TEXT_FIELD) ||
            (imageInsertMode == ImageInsertionModeEnum.INSERT_IN_TEXT_BODY)) {
            textContent.insertTextContent(textCursor, imageObject, false);
        }
        else {
            textContent.insertTextContent(textCursor, imageObject, true);
        }

        // Remove the temp ID which we don't need any more.
        bitMap.removeByName("MyTempID");

        ////////////////////////////////////////////////////////////////////
        // Make the document visible.
        ////////////////////////////////////////////////////////////////////

        System.out.println(
                "WriterDoc: Document construction finished - make it visible.");

        window.setVisible(true);

        return document;
    }

    /**
     * Save a given document to a specified file.
     * <p>
     * @param document
     *      The 'handle' to the document.
     * @param saveFile
     *      The full path of the file in which to save the document.
     *      If null, this method will do nothing.
     * @param format
     *      The format in which to save the document.
     * @param overwrite
     *      If true, and the file already exists, it will be
     *      overwritten.  Otherwise, if the file already exists an
     *      exception will be thrown.
     */
    public void saveDoc(
            XDocument document,
            String saveFile,
            DocumentFormatEnum format,
            boolean overwrite) throws java.lang.Exception {

        if ((saveFile == null) || (saveFile.trim().length() == 0)) { return; }
        if (! overwrite) {
            File f = new File(saveFile);
            if (f.exists()) {
                throw new java.lang.Exception(
                        "File " + saveFile + " already exists; overwriting disabled.");
            }
        }

        String saveFileURL = filePathToURL(saveFile);
        XStorable storable = (XStorable) UnoRuntime.queryInterface(
                XStorable.class, document);

        PropertyValue[] properties = new PropertyValue[1];
        PropertyValue p = new PropertyValue();
        p.Name = "FilterName";
        p.Value = format.getFormatCode();
        properties[0] = p;

        storable.storeAsURL(saveFileURL, properties);
    }

    /** Get a bookmarked field's <code>TextRange</code>. */
    private XTextRange getBookmarkTextRange(
            XBookmarksSupplier bookmarksSupplier, String bookmarkName)
        throws java.lang.Exception {

        XTextRange textRange = null;

        // Get the collection of bookmarks in the document.
        XNameAccess bookmarkNames = bookmarksSupplier.getBookmarks();

        // Find the bookmark having the given name.
        Object bmk = null;
        try {
            bmk = bookmarkNames.getByName(bookmarkName);
        } catch (NoSuchElementException e) {
        }
        if (bmk == null) {
            throw new java.lang.Exception(
                    "Cannot find bookmark '" + bookmarkName + "'");
        }

        // Get the bookmark's XTextContent.  It allows objects to be
        // inserted into a text and provides their location within a
        // text after insertion.

        XTextContent bookmarkContent = (XTextContent)
            UnoRuntime.queryInterface(XTextContent.class, bmk);

        // Get the bookmark's XTextRange.  It describes the object's
        // position within the text and provides access to the text.

        textRange = bookmarkContent.getAnchor();

        return textRange;
    }

    /** Convert a file path to URL format. */
    private String filePathToURL(String file) {
        File f = new File(file);
        StringBuffer sb = new StringBuffer("file:///");
        try {
            sb.append(f.getCanonicalPath().replace('\\', '/'));
        } catch (IOException e) {
        }
        return sb.toString();
    }

    /**
     * Dump a given <code>XPropertySet</code>.
     */
    private void showProperties(String title, XPropertySet pSet) {
        System.out.println("\n" + title + "\n");
        XPropertySetInfo info = pSet.getPropertySetInfo();
        Property[] props = info.getProperties();
        if (props != null) {
            try {
                for (int i=0; i < props.length; i++) {
                    Property p = props[i];
                    String value = "<null>";
                    try {
                        Object o = (Object) pSet.getPropertyValue(p.Name);
                        if (o != null) { value = o.toString(); }
                    } catch (java.lang.Exception e) {
                        value = "<null>";
                    }
                    System.out.println(
                            "   Name = " + p.Name +
                            ", Type = " + p.Type +
                            ", Value = " + value);
                }
            } catch (java.lang.Exception e) {
                e.printStackTrace();
            }
        }
    }

    /** Enumeration for document formats. */
    public enum DocumentFormatEnum {
        PDF ("PDF", "writer_pdf_Export"),
        MSWORD ("MS-Word", "MS Word 97");
        private String name;
        private String code;
        private static DocumentFormatEnum[] values = { PDF, MSWORD };

        private DocumentFormatEnum(String name, String code) {
            this.name = name;
            this.code = code;
        }
        public String getName() { return name; }
        public String getFormatCode() { return code; }
        public static DocumentFormatEnum[] getValues() { return values; }
    }

    /** Enumeration for techniques of inserting text into the document. */
    public enum TextInsertionModeEnum {
        REPLACE_ALL   ("ReplaceAll", "Insert text into a specific text field, replacing contents"),
        ADD_TEXT      ("AddText", "Append text to the existing contents of a text field"),
        ADD_SENTENCE  ("AddSentence", "Append text into a specific text field as a new sentence"),
        ADD_PARAGRAPH ("AddParagraph", "Append text into a specific text field as a new paragraph");
        private String name;
        private String desc;
        private static TextInsertionModeEnum[] values =
            { REPLACE_ALL, ADD_TEXT, ADD_SENTENCE, ADD_PARAGRAPH };

        private TextInsertionModeEnum(String name, String desc) {
            this.name = name;
            this.desc = desc;
        }
        public String getName() { return name; }
        public String getDesc() { return desc; }
        public static TextInsertionModeEnum[] getValues() { return values; }
    }

    /** Enumeration for techniques of inserting the image into a document. */
    public enum ImageInsertionModeEnum {
        INSERT_IN_TEXT_FIELD ("InsertInTextField", "Insert image into a specific text field"),
        INSERT_IN_TEXT_BODY  ("InsertInTextBody", "Insert image into the document body"),
        REPLACE_IN_TEXT_FIELD ("ReplaceInTextField", "Insert image into a specific text field, replacing existing content"),
        REPLACE_IN_TEXT_BODY ("ReplaceInTextBody", "Insert chart into the document body, replacing existing content");
        private String name;
        private String desc;
        private static ImageInsertionModeEnum[] values = {
            INSERT_IN_TEXT_FIELD,
            INSERT_IN_TEXT_BODY,
            REPLACE_IN_TEXT_FIELD,
            REPLACE_IN_TEXT_BODY
        };

        private ImageInsertionModeEnum(String name, String desc) {
            this.name = name;
            this.desc = desc;
        }
        public String getName() { return name; }
        public String getDesc() { return desc; }
        public static ImageInsertionModeEnum[] getValues() { return values; }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        String templateDoc =
            "C:/Documents and Settings/Rob/My Documents/EclipseProjects/OpenOffice/MyTemplateDoc.odt";

        WriterDoc doc = new WriterDoc();
        try {
            doc.createDoc("My Document Title", templateDoc, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
[/list]
Back to top
View user's profile Send private message
kvelentz
Newbie
Newbie


Joined: 23 Nov 2007
Posts: 1

PostPosted: Fri Nov 23, 2007 1:34 am    Post subject: Reply with quote

Hi rog123,

I'm new to java and I want to know where to find your imports.

import office.Chart.ChartInsertionModeEnum;
...
import com.sun.star.xml.dom.XDocument;

Thank you very much

Kostas
Back to top
View user's profile Send private message
hol.sten
Super User
Super User


Joined: 14 Nov 2004
Posts: 3533
Location: Hamburg, Germany

PostPosted: Sat Nov 24, 2007 4:36 am    Post subject: Reply with quote

kvelentz wrote:
import office.Chart.ChartInsertionModeEnum;

No idea. I've never found anything like that. Might be his own code.

kvelentz wrote:
import com.sun.star.xml.dom.XDocument;

unoil.jar in the subfolder program/classes of your OOo installation directory.
Back to top
View user's profile Send private message
fvarni
Newbie
Newbie


Joined: 18 Nov 2007
Posts: 1

PostPosted: Sun Nov 25, 2007 11:44 am    Post subject: Reply with quote

kvelentz wrote:
import office.Chart.ChartInsertionModeEnum;

The answer is there : http://www.oooforum.org/forum/viewtopic.phtml?t=61911
Back to top
View user's profile Send private message
robg123
General User
General User


Joined: 28 Aug 2007
Posts: 22

PostPosted: Mon Nov 26, 2007 2:18 pm    Post subject: Imports Reply with quote

Kvelentz:

Sorry for my delay in getting back to you.

Thank you hol.sten and fvarni for your assist!

I link to the following jar files under the /OpenOffice.org 2.2/program/classes: juh.jar, jurt.jar, ridl.jar, and unoil.jar.

As fvarni kindly pointed out, the source code for ChartInsertionModeEnum and other enumeration classes is shown near the bottom of the code sequence at http://www.oooforum.org/forum/viewtopic.phtml?t=61911 under the title "Example Java create a chart to insert into a Writer document". Each of these classes are actually in separate files within my application which is why ChartInsertionModeEnum appeared in the import statement you asked about. I should have included the code.

- Rob
Back to top
View user's profile Send private message
dcanibek
Newbie
Newbie


Joined: 04 Dec 2007
Posts: 4

PostPosted: Tue Dec 04, 2007 2:00 am    Post subject: bookmark Reply with quote

Thanks for the code, it is very helpful. but I have some hard time bookmarking text fields, actually i can not bookmark text field, so the text, images and chart is displayed at the body of the document not into the text fields.

If you explain how text fields bookmarked, I will be gladded.

Thanks..
Back to top
View user's profile Send private message Send e-mail Visit poster's website
robg123
General User
General User


Joined: 28 Aug 2007
Posts: 22

PostPosted: Wed Dec 05, 2007 1:53 pm    Post subject: Reply with quote

dcanibek:

Bookmarks can be inserted into your template document as follows:

(1) Run OpenOffice Writer and open your template document.

(2) Position your cursor where you want to insert a bookmark in the document.

(3) On the menu bar, open the "Insert..." menu and select "Bookmark...".

(4) In the resulting bookmark pop-up dialog, enter the name of the bookmark then click the "OK" button.

If you want the bookmark to be defined as a sequence of text, then drag your cursor to select the desired text sequence before invoking the Bookmark menu. Then when you do a bookmark insert programmatically via UNO, the entire text sequence can be replaced by the new value.

Note: check the Writer's Help on "Bookmarks" because there may be other easier ways to create bookmarks.

- Rob
Back to top
View user's profile Send private message
dcanibek
Newbie
Newbie


Joined: 04 Dec 2007
Posts: 4

PostPosted: Wed Dec 05, 2007 11:14 pm    Post subject: Reply with quote

thanks rob,

your code is very helpful, thanks alot but i still have problems with bookmarking a text field.

I actually have already tried to insert bookmark as you explain, i put 3 text field into my document and positioned the cursor each of them and inserted a bookmark but when i try to execute WriterDoc.java file, text, chart and picture are not inserted to the text fields, but they are inserted into the document body as the bookmarks are positioned at the top of the document.

i inserted bookmarks into the text fields and when i try to reach these bookmarks by right clicking on the status bar and selecting the bookmark i desired, cursor stays steady, it does not move as the bookmarks are all showing the place where the cursor is, but as i said before, WriterDoc inserted into the document body not into the text fields.

Thanks again,

Deger
Back to top
View user's profile Send private message Send e-mail Visit poster's website
robg123
General User
General User


Joined: 28 Aug 2007
Posts: 22

PostPosted: Fri Dec 07, 2007 9:23 am    Post subject: Reply with quote

I verified the code again and it seems to work OK for me. The only thing I can suggest at this point is that you step through your code and runtime and make sure that in the
"Example of inserting text into a field bookmarked in the template" code sequence, the call to 'getBookmarkTextRange' is actually finding the given bookmark. I.e., perhaps it is not finding the bookmark and defaulting to the document body.

- Rob
Back to top
View user's profile Send private message
dcanibek
Newbie
Newbie


Joined: 04 Dec 2007
Posts: 4

PostPosted: Fri Dec 07, 2007 1:06 pm    Post subject: Reply with quote

Thanks again Rob,

I prepare my template in ms word, when i insert form fields in to the template document, word automatically assigned that field a bookmark with the same name of the field's name. And by using this bookmark name i push the cursor to be positioned at the form field that i desired. This seems to be overcome my problem.

Thanks for your interest and quick responses..

Deger...
Back to top
View user's profile Send private message Send e-mail Visit poster's website
stoe
Newbie
Newbie


Joined: 14 Dec 2007
Posts: 3

PostPosted: Fri Dec 14, 2007 6:27 am    Post subject: Reply with quote

Hi there,

I am new to OOo and coded my last Java programm 2 years ago.
But now I got to set up a programm to convert OOo files to pdf.

My problem is, even if it sounds stupid, that I don't know where to get the 'handle' from.
Code:

    /**
     * ...
     * @param document
     *      The 'handle' to the document.
     * ...
     */
    public void saveDoc(
            XDocument document,
     ...


Can someone help me with that question.

Thx
stoe
_________________
So long and thanks for all the fish.
Back to top
View user's profile Send private message
hol.sten
Super User
Super User


Joined: 14 Nov 2004
Posts: 3533
Location: Hamburg, Germany

PostPosted: Fri Dec 14, 2007 12:10 pm    Post subject: Reply with quote

stoe wrote:
I got to set up a programm to convert OOo files to pdf.

Read this thread to get working examples to convert ODT or DOC or some other document types to PDF: http://www.oooforum.org/forum/viewtopic.phtml?t=66424

Read the OOo Developer's Guide to get a lot of Java examples: http://api.openoffice.org/DevelopersGuide/DevelopersGuide.html

Regards
hol.sten
Back to top
View user's profile Send private message
stoe
Newbie
Newbie


Joined: 14 Dec 2007
Posts: 3

PostPosted: Wed May 28, 2008 12:19 am    Post subject: Reply with quote

Hello out there,

after a longer break *lol* I'm back on a document management projekt.

I'm using OOo to create .odt files and I'm fine with that.
But everytime I try to save the created document I run into the same prolems I had when posting here the last time.

Could someone please give me a hint how I can get "The 'handle' to the document" in saveDoc.
Code:

    /**
     * ...
     * @param document     The 'handle' to the document.
     * ...
     */
    public void saveDoc(XDocument document, ...)
    {
         ...
     }


Thanks.
stoe
_________________
So long and thanks for all the fish.
Back to top
View user's profile Send private message
SergeM
Super User
Super User


Joined: 09 Sep 2003
Posts: 3211
Location: Troyes France

PostPosted: Wed May 28, 2008 12:41 am    Post subject: Reply with quote

Do you look for XDocument or XTextDocument ?
_________________
Linux & Windows OOo3.0
UNO & C++ : WIKI
http://wiki.services.openoffice.org/wiki/Using_Cpp_with_the_OOo_SDK
In French
http://wiki.services.openoffice.org/wiki/Documentation/FR/Cpp_Guide
Back to top
View user's profile Send private message Visit poster's website
stoe
Newbie
Newbie


Joined: 14 Dec 2007
Posts: 3

PostPosted: Wed May 28, 2008 1:50 am    Post subject: Reply with quote

SergeM wrote:
Do you look for XDocument or XTextDocument ?


Yes, I think so, but don't know how to do it.
I think it should be XDocument.

Could you tell me how I can get the XDocument handle to a just created document.

I created the document using
Code:
doc.createDoc(docTitle, templateDoc, true);

_________________
So long and thanks for all the fish.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    OOoForum.org Forum Index -> OpenOffice.org Code Snippets All times are GMT - 8 Hours
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group