Java PDF creator (Word OLE) - SDK sample


Related Articles Add comment Email article Print article

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 along with novaPDF.

Note: To be able to use the samples you must install novaPDF SDK as samples work only with it. Download it here: nova PDF SDK.

“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. Also, to avoid the “Logon failure: unknown user name or bad password” error, configure DCOM for remote access (detailed here) and make sure your firewall is not turned on.

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

package wordole;/* * j-interop can be found at http://www.j-interop.org/ * and it is an open source project * */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;publicclass Main {publicstatic String PROFILE_NAME = "Test Java and Word OLE";publicstaticint PROFILE_IS_PUBLIC = 0;/** * @param args the command line arguments */publicstaticvoid 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 dispatch = null; IJIComObject unknown = null;try{ JISession session = JISession.createSession(args[1], args[2], args[3]); session.useSessionSecurity(true); JIProgId pid = JIProgId.valueOf("novapi.NovaPdfOptions"); pid.setAutoRegistration(true); comStub = new JIComServer(pid, args[0], session); unknown = comStub.createInstance(); dispatch = (IJIDispatch) JIObjectFactory.narrowObject(unknown.queryInterface (IJIDispatch.IID)); JIString PRINTER = new JIString("<%novaPDF printer%>"); JIString UNAME = new JIString(""); JIString UKEY = new JIString(""); JIString UAPP = new JIString(""); JIString APPNID = new JIString("Word.Application"); dispatch.callMethod("Initialize2",new Object[]{PRINTER, UNAME, UKEY, UAPP}); JIVariant ap[] = dispatch.callMethodA("GetActiveProfile2",new Object[]{new JIVariant("", true),new JIVariant(0, true)}); String activeProfile = ap[2].getObjectAsString().getString();int nActivePublic = ap[1].getObjectAsInt();try{ dispatch.callMethod("CopyProfile2",new Object[]{new JIString(activeProfile),new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC});}catch(JIException come){ System.out.println("CopyProfile2:" + come.getMessage());}try{// set the copy profile as active profile ...  dispatch.callMethod("SetActiveProfile2",new Object[]{new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC});}catch(JIException come){ System.out.println("SetActiveProfile2:" + come.getMessage());}try{// and set some options  dispatch.callMethod("SetOptionString2",new Object[]{new JIString("Document Subject"),new JIString("Java Word OLE document"),new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC}); dispatch.callMethod("SetOptionString2",new Object[]{new JIString("Save File"),new JIString("novaPDFJavaDocument"),new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC}); dispatch.callMethod("SetOptionString2",new Object[]{new JIString("File Conflict Strategy"),new JIString("3"),new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC}); dispatch.callMethod("SetOptionString2",new Object[]{new JIString("Post Save Open"),new JIString("1"),new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC}); dispatch.callMethod("SetOptionString2",new Object[]{new JIString("Prompt Save Dialog"),new JIString("0"),new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC});}catch(JIException come){ System.out.println(come.getMessage());}//InitializeOLEUsage("Word.Application");  dispatch.callMethod("InitializeOLEUsage",new Object[]{APPNID}); dispatch.callMethod("LicenseOLEServer"); MSWord word = new MSWord(args[0], args, dispatch, PRINTER); word.startWord(); word.showWord(); word.performOp(); word.quitAndDestroy();try{ dispatch.callMethod("SetActiveProfile2",new Object[]{new JIString(activeProfile), nActivePublic});}catch(JIException come){ System.out.println("SetActiveProfile2" + come.getMessage());}try{ dispatch.callMethod("DeleteProfile2",new Object[]{new JIString(PROFILE_NAME), PROFILE_IS_PUBLIC});}catch(JIException come){ System.out.println("DeleteProfile2:" + come.getMessage());} 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;publicclass 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);}publicvoid startWord()throws JIException { unknown = comStub.createInstance(); dispatch = (IJIDispatch) JIObjectFactory.narrowObject(unknown.queryInterface(IJIDispatch.IID));}publicvoid showWord()throws JIException {int dispId = dispatch.getIDsOfNames("Visible"); JIVariant variant = new JIVariant(Boolean.FALSE); dispatch.put(dispId, variant); PDF.callMethod("LicenseOLEServer");}publicvoid 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");}privatevoid sleep(int sec)throws InterruptedException { System.out.println("Sleeping "+sec+" second(s)..."); Thread.sleep((int)(sec * 1000));}/** * @throws JIException */publicvoid 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());}}

Related articles

Comments