Limited time promo

Java Sample - Word OLE

English

This help topic applies only to novaPDF. If you don't have it yet, you must download it first.

Download now Buy licenses
Mar 29, 2022
novaPDF 11.x
We strive to keep our help as accurate as possible. If you notice any inconsistencies or outdated info please let us know.
The Word OLE (Java) SDK sample is a basic Java console application that converts a MS Word document (in this sample the default location for the source document is C:\temp\test.doc) to PDF using Word OLE automation and j-Interop.
“j-Interop is a Java Open Source library (under LGPL) that implements the DCOM wire protocol (MSRPC) to enable development of Pure, Bi-Directional, Non-Native Java applications which can interoperate with any COM component.“ j-Interop can be found at http://www.j-interop.org/
Note
If you encounter problems or have questions on using j-Interop, visit their FAQ page at http://www.j-interop.org/faq.html
Also, to avoid the “Logon failure: unknown user name or bad password” error, configure DCOM for remote access (detailed here - http://j-integra.intrinsyc.com/support/com/doc/remoteaccess.html#winxp) and make sure your firewall is not turned on.

Source code for Word OLE sample (Main.java):

package wordole;

import java.io.File;
import java.util.logging.Level;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JIProgId;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.JIObjectFactory;
import org.jinterop.dcom.impls.automation.IJIDispatch;

public class Main {

    public static String PROFILE_NAME = "Test Java and Word OLE";
    public static int PROFILE_IS_PUBLIC = 0;

    public static long NOVAPDF_DOCINFO_SUBJECT = 68;
    public static String NOVAPDF_INFO_SUBJECT = "Java OLE Word Document Subject";
    
    public static long NOVAPDF_SAVE_FILE_NAME = 104;
    public static long NOVAPDF_SAVE_FILEEXIST_ACTION = 108;
    public static long FILE_CONFLICT_STRATEGY_AUTONUMBER_NEW = 1;
    public static long NOVAPDF_INFO_VIEWER_ENABLE = 8;
    public static long NOVAPDF_SAVE_PROMPT_TYPE = 101;
    public static long PROMPT_SAVE_SIMPLE = 2;
   /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        if (args.length < 4) {
            System.out.println("Please provide address domain username password");
            return;
        }
        File docFile = new File("c:\\temp\\test.doc");
        if (!docFile.exists()) {
            System.out.println("c:\\temp\\test.doc file does not exist");
            return;
        }
        
        //disable J-Interop Log
        try {
            JISystem.getLogger().setLevel(Level.INFO);
            JISystem.setInBuiltLogHandler(false);
        } catch (Exception e) {
            //System.out.println(e.getMessage());
        }

        JIComServer comStub = null;
        IJIDispatch pNovaDispatch = null;
        IJIComObject unknown = null;

        try {
            JISession session = JISession.createSession(args[1], args[2], args[3]);
            session.useSessionSecurity(true);

            JIProgId pid = JIProgId.valueOf("novapi11.NovaPdfOptions11");
            pid.setAutoRegistration(true);

            comStub = new JIComServer(pid, args[0], session);
            unknown = comStub.createInstance();

            pNovaDispatch = (IJIDispatch) JIObjectFactory.narrowObject(unknown.queryInterface(IJIDispatch.IID));

            //INITIALIZE
            
            JIString PRINTER = new JIString("novaPDF SDK 11");
            JIString APPNID = new JIString("Word.Application");
            pNovaDispatch.callMethod("Initialize2", new Object[]{PRINTER},  new JIString(""));

            //GET ACTIVE PROFILE

            String oldActiveProfile = "";

            try {
                JIVariant ap[] = pNovaDispatch.callMethodA("GetActiveProfile2", new Object[]{new JIVariant("", true)});
                oldActiveProfile = ap[1].getObjectAsString().getString();
            } catch ( JIException except ) {
                System.out.println("GetActiveProfile2");
                except.printStackTrace() ;
            }

            String activeProfile = "";

            //ADD A NEW PROFILE
            try {
                JIVariant ap[] = pNovaDispatch.callMethodA("AddProfile2", new Object[]{new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC, new JIVariant("", true)});
                activeProfile = ap[1].getObjectAsString().getString();
            } catch (JIException except) {
                System.out.println("AddProfile2");
                 except.printStackTrace();
            }

            //LOAD PROFILE
            try {
                pNovaDispatch.callMethod("LoadProfile2", new Object[]{new JIString(activeProfile)});
            } catch (JIException except) {
                System.out.println("LoadProfile2");
                except.printStackTrace();
            }

            //CHANGE SOME OPTIONS
            try {
                // and set some options
                pNovaDispatch.callMethod("SetOptionString2", new Object[]{NOVAPDF_DOCINFO_SUBJECT, new JIString(NOVAPDF_INFO_SUBJECT)});
                pNovaDispatch.callMethod("SetOptionString2", new Object[]{NOVAPDF_SAVE_FILE_NAME, new JIString("novaPDFJavaDocument")});
                pNovaDispatch.callMethod("SetOptionLong", new Object[]{NOVAPDF_SAVE_FILEEXIST_ACTION, FILE_CONFLICT_STRATEGY_AUTONUMBER_NEW});
                pNovaDispatch.callMethod("SetOptionBool", new Object[]{NOVAPDF_INFO_VIEWER_ENABLE, 1});
                pNovaDispatch.callMethod("SetOptionLong", new Object[]{NOVAPDF_SAVE_PROMPT_TYPE, PROMPT_SAVE_SIMPLE});
            } catch (JIException except) {
                System.out.println("Set options");
                except.printStackTrace();
            }
            
            //SAVE PROFILE
            try {
                pNovaDispatch.callMethod("SaveProfile2");
            } catch (JIException except) {
                System.out.println("SaveProfile2");
                 except.printStackTrace();
            }
            
            //SET IT AS ACTIVE PROFILE
            try {
                // set the copy profile as active profile ...
                pNovaDispatch.callMethod("SetActiveProfile2", new Object[]{new JIString(activeProfile)});
            } catch (JIException except) {
                System.out.println("SetActiveProfile2");
                except.printStackTrace();
            }
            //InitializeOLEUsage("Word.Application");
            pNovaDispatch.callMethod("InitializeOLEUsage", new Object[]{APPNID});
            pNovaDispatch.callMethod("LicenseOLEServer");

            MSWord word = new MSWord(args[0], args, pNovaDispatch, PRINTER);
            word.startWord();
            word.showWord();

            word.performOp();
            word.quitAndDestroy();

            //RESTORE PREVIOUS ACTIVE PROFILE
            try {
                if(oldActiveProfile.length() > 0) {
                    pNovaDispatch.callMethod("SetActiveProfile2", new Object[]{new JIString(oldActiveProfile)});
                }
            } catch (JIException except) {
                System.out.println("SetActiveProfile2 Old");
                except.printStackTrace();
            }

            //DELETE THE NEW PROFILE

            try {
                pNovaDispatch.callMethod("DeleteProfile2", new Object[]{new JIString(activeProfile)});
            } catch (JIException except) {
                System.out.println("DeleteProfile2");
                except.printStackTrace();
            }
            System.out.println("Done!");

        } catch (Exception e) {
            System.out.println("---UPS---");
            e.printStackTrace();
        }
    }
}
Source code for Word OLE sample (MSWord.java):

package wordole;
/*
 * j-interop can be found at http://www.j-interop.org/
 * and it is an open source project
 *
 */
import java.net.UnknownHostException;
import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.IJIComObject;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JIProgId;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.core.JIString;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.impls.JIObjectFactory;
import org.jinterop.dcom.impls.automation.IJIDispatch;

public class MSWord {

    private JIComServer comStub = null;

    private IJIDispatch dispatch = null;

    private IJIComObject unknown = null;

    private IJIDispatch PDF = null;

    private JIString PRINTER = null;

    public MSWord(String address, String[] args, IJIDispatch PDF, JIString PRINTER) throws JIException, UnknownHostException {

        this.PDF = PDF;
        this.PRINTER = PRINTER;

        JISession session = JISession.createSession(args[1], args[2], args[3]);
        session.useSessionSecurity(true);
        comStub = new JIComServer(JIProgId.valueOf("Word.Application"), address, session);
    }

    public void startWord() throws JIException {
        unknown = comStub.createInstance();
        dispatch = (IJIDispatch) JIObjectFactory.narrowObject(unknown.queryInterface(IJIDispatch.IID));
    }

    public void showWord() throws JIException {
        int dispId = dispatch.getIDsOfNames("Visible");
        JIVariant variant = new JIVariant(Boolean.FALSE);
        dispatch.put(dispId, variant);
        PDF.callMethod("LicenseOLEServer");
    }

    public void performOp() throws JIException, InterruptedException {

        /* JISystem config *
         *
         */
        JISystem.setJavaCoClassAutoCollection(true);



        System.out.println(((JIVariant) dispatch.get("Version")).getObjectAsString().getString());
        System.out.println(((JIVariant) dispatch.get("Path")).getObjectAsString().getString());
        JIVariant variant = dispatch.get("Documents");

        System.out.println("Open document...");
        IJIDispatch documents = (IJIDispatch) JIObjectFactory.narrowObject(variant.getObjectAsComObject());
        JIString filePath = new JIString("c:\\temp\\test.doc");
        JIVariant variant2[] = documents.callMethodA("open", new Object[] { filePath, JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() ,JIVariant.OPTIONAL_PARAM() , JIVariant.OPTIONAL_PARAM() });

        System.out.println("doc opened");
        //ActivePrinter
        dispatch.put("ActivePrinter", new Object[]{PRINTER});

        sleep(5);
        System.out.println("Get content...");
        IJIDispatch document = (IJIDispatch) JIObjectFactory.narrowObject(variant2[0].getObjectAsComObject());

        sleep(5);
        System.out.println("Printing...");
        document.callMethod("PrintOut", new Object[] {1});

        System.out.println("Closing document...");
        document.callMethod("Close");

    }

    private void sleep(int sec) throws InterruptedException {
        System.out.println("Sleeping "+sec+" second(s)...");
        Thread.sleep( (int)(sec  * 1000) );
    }

    /**
     * @throws JIException
     */
    public void quitAndDestroy() throws JIException {
        System.out.println("Quit...");
        dispatch.callMethod("Quit", new Object[] { new JIVariant(-1, true), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM() });
        JISession.destroySession(dispatch.getAssociatedSession());
    }

}