Use Jacob to call Windows COM objects, convert Office files to PDF, HTML, and more

Source: Internet
Author: User



1. Introduction





Jacob is the abbreviation for Java-com Bridge, which builds a bridge between Java and Microsoft's COM components. Using Jacob's own DLL dynamic link library, and through the way of JNI implementation of the Java platform on the COM program calls. As for what is COM component, let's own Google.

2. Installation and Configuration

Jacob is an open source software, its official site is: http://danadler.com/jacob/You can download the source code research, you can also directly download the compiled binary files.

Download the package Jacob_x.x.zip, after extracting a few files: Jacob.jar, Jacob-x.x-m2-x86.dll
Copy the Jacob-x.x-m2-x86.dll to the bin directory under%java_home%, where%java_home% is the directory where the JDK is installed. Then you can use it by referencing Jacob.jar directly in the Java IDE.


3. Convert Word to PDF, HTML, txt example





package com.shanhy.demo.windowsoffice;
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
* *
*
*Put jacob.dll into the bin directory of JDK
*Put jacob.jar in the buildpath of the project (put the web project in the WEB-INF \ lib directory)
*
*@ author Shan Hongyu
*
* /
public class ConvertToPdf {
//Parameter value of word conversion document format: 17 is PDF, 8 is HTML, 2 is TXT (the supported formats are not limited to this, other formats are listed temporarily)
Static final int wdformatpdf = 17; / / pdf
Static final int wdformatthtml = 8; / / HTML format
Static final int wdformattxt = 2; / / TXT
* *
*Word document conversion
*
* @param fromfileName
* @param toFileName
* @author SHANHY
* /
public void wordConvert(String fromfileName, String toFileName) {
System. Out. Println ("start word...");
ComThread.InitSTA();
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null;
Try {
App = new activexcomponent ("word. Application"); / / create a word object
App. Setproperty ("visible", new variant (false)); / / invisible open word
App. Setproperty ("automationsecurity", new variant (3)); / / disable macro
Dispatch docs = app. Getproperty ("documents"). Todispatch(); / / get file properties
System. Out. Println ("open document > >" + fromfilename);
//The third parameter of object [] is "open read only"
doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
new Object[] { fromfileName, new Variant(false), new Variant(true) }, new int[1]).toDispatch();
File tofile = new File(toFileName);
if (tofile.exists()) {
tofile.delete();
}
int formatValue = -1;
if(toFileName.toLowerCase().endsWith(".pdf")){
formatValue = wdFormatPDF;
}else if(toFileName.toLowerCase().endsWith(".html")){
formatValue = wdFormatHTML;
}else if(toFileName.toLowerCase().endsWith(".txt")){
formatValue = wdFormatTXT;
}else{
formatValue = -1;
}
if(formatValue != -1){
System. Out. Println ("conversion document [" + fromfilename + "] > > [" + tofilename + "]);
Dispatch.invoke(doc, "SaveAs", Dispatch.Method,
new Object[] { toFileName, new Variant(formatValue) }, new int[1]);
}else{
System. Out. Println ("converting files to target documents is not supported! ["+fromfileName+"] >>> ["+toFileName+"]");
}
long end = System.currentTimeMillis();
System. Out. Println ("time usage:" + (end - start) + "Ms.");
} catch (Exception e) {
e.printStackTrace();
System. Out. Println ("======== error: document conversion failed:" + e.getmessage());
} finally {
Dispatch.call(doc, "Close", false);
System.out.println ("close document");
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//Without this sentence, the winword.exe process will not shut down
ComThread.Release();
ComThread.quitMainSTA();
}
* *
*PPT (PowerPoint) document conversion
*
* @param fromfileName
* @param toFileName
* @author SHANHY
* /
public void pptConvert(String fromfileName, String toFileName) {
System. Out. Println ("start ppt...");
ComThread.InitSTA();
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null;
Try {
App = new activexcomponent ("word. Application"); / / create a word object
App. Setproperty ("visible", new variant (false)); / / invisible open word
App. Setproperty ("automationsecurity", new variant (3)); / / disable macro
Dispatch docs = app. Getproperty ("documents"). Todispatch(); / / get file properties
System. Out. Println ("open document > >" + fromfilename);
//The third parameter of object [] is "open read only"
doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
new Object[] { fromfileName, new Variant(false), new Variant(true) }, new int[1]).toDispatch();
File tofile = new File(toFileName);
if (tofile.exists()) {
tofile.delete();
}
int formatValue = -1;
if(toFileName.toLowerCase().endsWith(".pdf")){
formatValue = wdFormatPDF;
}else if(toFileName.toLowerCase().endsWith(".html")){
formatValue = wdFormatHTML;
}else if(toFileName.toLowerCase().endsWith(".txt")){
formatValue = wdFormatTXT;
}else{
formatValue = -1;
}
if(formatValue != -1){
System. Out. Println ("conversion document [" + fromfilename + "] > > [" + tofilename + "]);
Dispatch.invoke(doc, "SaveAs", Dispatch.Method,
new Object[] { toFileName, new Variant(formatValue) }, new int[1]);
}else{
System. Out. Println ("converting files to target documents is not supported! ["+fromfileName+"] >>> ["+toFileName+"]");
}
long end = System.currentTimeMillis();
System. Out. Println ("time usage:" + (end - start) + "Ms.");
} catch (Exception e) {
e.printStackTrace();
System. Out. Println ("======== error: document conversion failed:" + e.getmessage());
} finally {
Dispatch.call(doc, "Close", false);
System.out.println ("close document");
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//Without this sentence, the winword.exe process will not shut down
ComThread.Release();
ComThread.quitMainSTA();
}
public static void main(String[] args) {
ConvertToPdf d = new ConvertToPdf();
d.wordConvert("g:\\test.docx", "g:\\test.pdf");
}
}

A simple example of reading and writing word







import com.jacob.activeX.ActiveXComponent; 
import com.jacob.com.Variant; 
import com.jacob.com.Dispatch; 

public class Word { 

    String strDir = "c:jacob_1.9"; 
    String strInputDoc = strDir + "file_in.doc"; 
    String strOutputDoc = strDir + "file_out.doc"; 
    String strOldText = "[label:import:1]"; 
    String strNewText = 
            "I am some horribly long sentence, so long that [insert anything]"; 
    boolean isVisible = true; 
    boolean isSaveOnExit = true; 

    public Word() { 
        ActiveXComponent oWord = new ActiveXComponent("Word.Application"); 
        oWord.setProperty("Visible", new Variant(isVisible)); 
        Dispatch oDocuments = oWord.getProperty("Documents").toDispatch(); 
        Dispatch oDocument = Dispatch.call(oDocuments, "Open", strInputDoc). 
                             toDispatch(); 
        Dispatch oSelection = oWord.getProperty("Selection").toDispatch(); 
        Dispatch oFind = oWord.call(oSelection, "Find").toDispatch(); 
        Dispatch.put(oFind, "Text", strOldText); 
        Dispatch.call(oFind, "Execute"); 
        Dispatch.put(oSelection, "Text", strNewText); 
        Dispatch.call(oSelection, "MoveDown"); 
        Dispatch.put(oSelection, "Text", 
                     "nSo we got the next line including BR.n"); 

        Dispatch oFont = Dispatch.get(oSelection, "Font").toDispatch(); 
        Dispatch.put(oFont, "Bold", "1"); 
        Dispatch.put(oFont, "Italic", "1"); 
        Dispatch.put(oFont, "Underline", "0"); 

        Dispatch oAlign = Dispatch.get(oSelection, "ParagraphFormat"). 
                          toDispatch(); 
        Dispatch.put(oAlign, "Alignment", "3"); 
        Dispatch oWordBasic = (Dispatch) Dispatch.call(oWord, "WordBasic"). 
                              getDispatch(); 
        Dispatch.call(oWordBasic, "FileSaveAs", strOutputDoc); 
        Dispatch.call(oDocument, "Close", new Variant(isSaveOnExit)); 
        oWord.invoke("Quit", new Variant[0]); 
    } 

    public static void main(String[] args) { 
        Word word = new Word(); 
    } 
} 

4, the structure of Jacob.jar

Jacob consists of two parts:

Com.jacob.activeX:ActiveXComponent class
Com.jacob.com: Other classes and elements

5. Jacob Class

Jacob's structure is simple and consists of the following classes:

Activexcomponent Class: Encapsulates the dispatch object, which is used to create a Java object that encapsulates a COM component object
Dispatch Class: Used to point to the encapsulated MS data structure. The common method has call,subcall,get,invoke ... The use method is described later.
Variant Class: The Variant data type used to map com. Provides data exchange between Java and COM.

COMException Class: Exception classes

6. Jacob Method

The method used to access the Com/dll object, reading and modifying the properties of the Com/dll object.

Call method: Belongs to the Dispatch class. The method used to access the Com/dll object. The method is overloaded to make it easy to call on different occasions. Returns the value of a variant type.
Callsub method: Use the same way as call, but it does not return a value.
Get method: Reads the property value of a COM object and returns a Variant type value.
Put method: Sets the property value of the COM object.
Another use of Invoke Method:call is more complex.
Another use of Invokesub Method:subcall
GetProperty method: Belongs to the Activexcomponent class, reads the property value, returns a Variant type value.

SetProperty method: Belongs to the Activexcomponent class and sets the property value.

One thing to note: When using Jacob, it is important that users have Office-installed applications. Otherwise, the Java-com bridge cannot be built, and thus cannot be resolved.








Part of the content reference: http://www.cnblogs.com/vulcans/archive/2009/09/08/1562588.html






Use Jacob to call Windows COM objects, convert Office files to PDF, HTML, and more


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.