(Reprint) java Operates word Documents (jacob)

Keywords: Java jvm Windows network

Reproduced from http://wibiline.iteye.com/blog/1725492


For project needs, users download word documents from the system, which are limited and encrypted. Users can only fill in content in a fixed location. The system is now required to verify whether the uploaded attachments are downloaded from the system.

Idea: Documents on the system are all added with a fixed bookmark. When users upload documents, check whether the document contains the bookmark.

Using jacob to manipulate word documents

 

JACOB (java-com bridge) is a bridge between JAVA and Microsoft COM interface. Using JACOB allows any JVM to access COM objects, enabling JAVA applications to call COM objects.

Download address: http://sourceforge.net/projects/jacob-project/

 

Among them, jacob-1.16.1-x64.dll is used on 64-bit machines and jacob-1.16.1-x86.dll is used on 32-bit machines.

The dll is placed in the C: Windows system 32 directory. jacob.jar under application lib

Test code

  1. ActiveXComponent    word = null;  
  2. try {  
  3.         word = new ActiveXComponent("Word.Application");  
  4.         System.out.println("jacob Current version:"+word.getBuildVersion());  
  5. }catch(Exception e ){  
  6.          e.printStackTrace();  
  7. }  

Next, I will post some common codes on the Internet + some methods of self-organizing (blurred inquiry bookmarks, etc.)

Note the method of inserting bookmark + bookmark value. First insert the bookmark value, then select the bookmark value, and then insert the bookmark. In this way, the bookmark value can be obtained by signing the book. Otherwise, according to many methods on the network, the bookmark value can not be obtained or empty. Because a bookmark value can be either a point or a large piece of content.

  1. import java.io.File;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4.   
  5. import com.gdcn.bpaf.common.helper.StringHelper;  
  6. import com.jacob.activeX.ActiveXComponent;  
  7. import com.jacob.com.ComThread;  
  8. import com.jacob.com.Dispatch;  
  9. import com.jacob.com.Variant;  
  10. /** 
  11.  *  * 
  12.  * <p>Description: {jacob Operating word class}</p> 
  13.  * 
  14.  * <p>Copyright: Copyright (c) 2011</p> 
  15.  *  
  16.  * <p>CreateDate: 2012-6-28</p> 
  17.  * 
  18.  * @author Beny 
  19.  * @version 1.0 
  20.  */  
  21.   
  22. public class JacobHelper {  
  23.     //word document  
  24.     private Dispatch doc;  
  25.   
  26.     //word Running Program Object  
  27.     private ActiveXComponent word;  
  28.   
  29.     //All word document collections  
  30.     private Dispatch documents;  
  31.   
  32.     //Selected range or insertion point  
  33.     private Dispatch selection;  
  34.   
  35.     private boolean saveOnExit = true;  
  36.   
  37.     public JacobHelper(boolean visible) throws Exception {  
  38.         ComThread.InitSTA();//Thread start  
  39.         if (word == null) {  
  40.             word = new ActiveXComponent("Word.Application");  
  41.             word.setProperty("Visible"new Variant(visible)); //Open word invisibly  
  42.             word.setProperty("AutomationSecurity"new Variant(3)); //Forbidden macro  
  43.         }  
  44.         if (documents == null)  
  45.             documents = word.getProperty("Documents").toDispatch();  
  46.     }  
  47.   
  48.     /** 
  49.      * Setting exit parameters 
  50.      *  
  51.      * @param saveOnExit 
  52.      *            boolean true-Save the file when you quit, false - do not save the file when you quit 
  53.      */  
  54.     public void setSaveOnExit(boolean saveOnExit) {  
  55.         this.saveOnExit = saveOnExit;  
  56.     }  
  57.   
  58.     /** 
  59.      * Create a new word document 
  60.      *  
  61.      */  
  62.     public void createNewDocument() {  
  63.         doc = Dispatch.call(documents, "Add").toDispatch();  
  64.         selection = Dispatch.get(word, "Selection").toDispatch();  
  65.     }  
  66.   
  67.     /** 
  68.      * Open an existing document 
  69.      *  
  70.      * @param docPath 
  71.      */  
  72.     public void openDocument(String docPath) {  
  73. //      closeDocument();  
  74.         doc = Dispatch.call(documents, "Open", docPath).toDispatch();  
  75.         selection = Dispatch.get(word, "Selection").toDispatch();  
  76.     }  
  77.   
  78.     /** 
  79.      * Open an encrypted document in read-only mode 
  80.      *  
  81.      * @param docPath-Full name of file 
  82.      * @param pwd-Password 
  83.      */  
  84.     public void openDocumentOnlyRead(String docPath, String pwd)  
  85.             throws Exception {  
  86. //      closeDocument();  
  87.         doc = Dispatch.callN(  
  88.                 documents,  
  89.                 "Open",  
  90.                 new Object[] { docPath, new Variant(false), new Variant(true),  
  91.                         new Variant(true), pwd, ""new Variant(false) })  
  92.                 .toDispatch();  
  93.         selection = Dispatch.get(word, "Selection").toDispatch();  
  94.     }  
  95.     /** 
  96.      * Open an encrypted document 
  97.      * @param docPath 
  98.      * @param pwd 
  99.      * @throws Exception 
  100.      */  
  101.     public void openDocument(String docPath, String pwd) throws Exception {  
  102. //      closeDocument();  
  103.         doc = Dispatch.callN(  
  104.                 documents,  
  105.                 "Open",  
  106.                 new Object[] { docPath, new Variant(false), new Variant(false),  
  107.                         new Variant(true), pwd }).toDispatch();  
  108.         selection = Dispatch.get(word, "Selection").toDispatch();  
  109.     }  
  110.   
  111.     /** 
  112.      * Find text from the selected content or insertion point 
  113.      *  
  114.      * @param toFindText 
  115.      *            Text to look for 
  116.      * @return boolean true-Find and select the text, false - No text found 
  117.      */  
  118.     @SuppressWarnings("static-access")  
  119.     public boolean find(String toFindText) {  
  120.         if (toFindText == null || toFindText.equals(""))  
  121.             return false;  
  122.         //Start with the location of selection  
  123.         Dispatch find = word.call(selection, "Find").toDispatch();  
  124.         //Setting up what to look for  
  125.         Dispatch.put(find, "Text", toFindText);  
  126.         //Look forward  
  127.         Dispatch.put(find, "Forward""True");  
  128.         //Format  
  129.         Dispatch.put(find, "Format""True");  
  130.         //Case matching  
  131.         Dispatch.put(find, "MatchCase""True");  
  132.         //Full-word matching  
  133.         Dispatch.put(find, "MatchWholeWord""false");  
  134.         //Find and select  
  135.         return Dispatch.call(find, "Execute").getBoolean();  
  136.     }  
  137.   
  138.     /** 
  139.      * Set the selected content to replace text 
  140.      *  
  141.      * @param toFindText 
  142.      *            Find strings 
  143.      * @param newText 
  144.      *            Contents to be replaced 
  145.      * @return 
  146.      */  
  147.     public boolean replaceText(String toFindText, String newText) {  
  148.         if (!find(toFindText))  
  149.             return false;  
  150.         Dispatch.put(selection, "Text", newText);  
  151.         return true;  
  152.     }  
  153.   
  154.     /** 
  155.      * Global Replacement Text 
  156.      *  
  157.      * @param toFindText 
  158.      *            Find strings 
  159.      * @param newText 
  160.      *            Contents to be replaced 
  161.      */  
  162.     public void replaceAllText(String toFindText, String newText) {  
  163.         while (find(toFindText)) {  
  164.             Dispatch.put(selection, "Text", newText);  
  165.             Dispatch.call(selection, "MoveRight");  
  166.         }  
  167.     }  
  168.   
  169.     /** 
  170.      * Insert a string at the current insertion point 
  171.      *  
  172.      * @param newText 
  173.      *            New string to insert 
  174.      */  
  175.     public void insertText(String newText) {  
  176.         Dispatch.put(selection, "Text", newText);  
  177.     }  
  178.   
  179.   
  180.   
  181.     /** 
  182.      * Set the font for the current selection 
  183.      *  
  184.      * @param boldSize 
  185.      * @param italicSize 
  186.      * @param underLineSize 
  187.      *            Underline 
  188.      * @param colorSize 
  189.      *            Font color 
  190.      * @param size 
  191.      *            font size 
  192.      * @param name 
  193.      *            Font name 
  194.      * @param hidden 
  195.      *            Is it hidden? 
  196.      */  
  197.     public void setFont(boolean bold, boolean italic, boolean underLine,  
  198.             String colorSize, String size, String name,boolean hidden) {  
  199.         Dispatch font = Dispatch.get(selection, "Font").toDispatch();  
  200.         Dispatch.put(font, "Name"new Variant(name));  
  201.         Dispatch.put(font, "Bold"new Variant(bold));  
  202.         Dispatch.put(font, "Italic"new Variant(italic));  
  203.         Dispatch.put(font, "Underline"new Variant(underLine));  
  204.         Dispatch.put(font, "Color", colorSize);  
  205.         Dispatch.put(font, "Size", size);  
  206.         Dispatch.put(font, "Hidden", hidden);  
  207.     }  
  208.   
  209.   
  210.     /** 
  211.      * Files are saved or saved as 
  212.      *  
  213.      * @param savePath 
  214.      *            Save or save as a path 
  215.      */  
  216.     public void save(String savePath) {  
  217.         Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),  
  218.                 "FileSaveAs", savePath);  
  219.     }  
  220.   
  221.     /** 
  222.      * Files are saved in html format 
  223.      *  
  224.      * @param savePath 
  225.      * @param htmlPath 
  226.      */  
  227.     public void saveAsHtml(String htmlPath) {  
  228.         Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {  
  229.                 htmlPath, new Variant(8) }, new int[1]);  
  230.     }  
  231.   
  232.     /** 
  233.      * close document 
  234.      *  
  235.      * @param val 
  236.      *            0 Do not save modifications - 1. Save modifications - 2. Indicate whether to save modifications 
  237.      */  
  238.     public void closeDocument(int val) {  
  239.         Dispatch.call(doc, "Close"new Variant(val));//Note: Douments, not doc s  
  240.         documents = null;  
  241.         doc = null;  
  242.     }  
  243.   
  244.     /** 
  245.      * Close the current word document 
  246.      *  
  247.      */  
  248.     public void closeDocument() {  
  249.         if (documents != null) {  
  250.             Dispatch.call(documents, "Save");  
  251.             Dispatch.call(documents, "Close"new Variant(saveOnExit));  
  252.             documents = null;  
  253.             doc = null;  
  254.         }  
  255.     }  
  256.   
  257.     public void closeDocumentWithoutSave() {  
  258.         if (documents != null) {  
  259.             Dispatch.call(documents, "Close"new Variant(false));  
  260.             documents = null;  
  261.             doc = null;  
  262.         }  
  263.     }  
  264.   
  265.     /** 
  266.      * Save and close all applications 
  267.      *  
  268.      */  
  269.     public void close() {  
  270.         closeDocument(-1);  
  271.         if (word != null) {  
  272. //          Dispatch.call(word, "Quit");  
  273.             word.invoke("Quit"new Variant[] {});  
  274.             word = null;  
  275.         }  
  276.         selection = null;  
  277.         documents = null;  
  278.         ComThread.Release();//Release the com thread. According to jacob's help document, thread recycling at com is not handled by java's garbage collector  
  279.   
  280.     }  
  281.     /** 
  282.      * Print the current word document 
  283.      *  
  284.      */  
  285.     public void printFile() {  
  286.         if (doc != null) {  
  287.             Dispatch.call(doc, "PrintOut");  
  288.         }  
  289.     }  
  290.   
  291.     /** 
  292.      * Protect the current file, if it does not exist, use expression.Protect(Type, NoReset, Password) 
  293.      *  
  294.      * @param pwd 
  295.      * @param type 
  296.      *            WdProtectionType One of the constants (int type, read-only): 
  297.      *            1-wdAllowOnlyComments  Endorsement only 
  298.      *            2-wdAllowOnlyFormFields Fill in the form only 
  299.      *            0-wdAllowOnlyRevisions Revision only 
  300.      *            -1-wdNoProtection No protection. 
  301.      *            3-wdAllowOnlyReading read-only 
  302.      *  
  303.      */  
  304.     public void protectedWord(String pwd,String type) {  
  305.         String protectionType = Dispatch.get(doc, "ProtectionType").toString();  
  306.         if (protectionType.equals("-1")) {  
  307.             Dispatch.call(doc, "Protect", Integer.parseInt(type), new Variant(true),pwd);  
  308.         }  
  309.     }  
  310.   
  311.     /** 
  312.      * Remove document protection if it exists 
  313.      *  
  314.      * @param pwd 
  315.      *            WdProtectionType One of the constants (int type, read-only): 
  316.      *            1-wdAllowOnlyComments  Endorsement only 
  317.      *            2-wdAllowOnlyFormFields Fill in the form only 
  318.      *            0-wdAllowOnlyRevisions Revision only 
  319.      *            -1-wdNoProtection No protection. 
  320.      *            3-wdAllowOnlyReading read-only 
  321.      *  
  322.      */  
  323.     public void unProtectedWord(String pwd) {  
  324.         String protectionType = Dispatch.get(doc, "ProtectionType").toString();  
  325.         if (!protectionType.equals("0")&&!protectionType.equals("-1")) {  
  326.             Dispatch.call(doc, "Unprotect", pwd);  
  327.         }  
  328.     }  
  329.     /** 
  330.      * Protection Type of Return Document 
  331.      * @return 
  332.      */  
  333.     public String getProtectedType(){  
  334.         return Dispatch.get(doc, "ProtectionType").toString();  
  335.     }  
  336.   
  337.     /** 
  338.      * Setting word Document Security Level 
  339.      *  
  340.      * @param value 
  341.      *            1-msoAutomationSecurityByUI Use the security settings specified in the Security dialog box. 
  342.      *            2-msoAutomationSecurityForceDisable 
  343.      *            Disable all macros in all files opened by the program without showing any security alerts. 3-mso Automation Security Low 
  344.      *            Enable all macros, which is the default when starting the application. 
  345.      */  
  346.     public void setAutomationSecurity(int value) {  
  347.         word.setProperty("AutomationSecurity"new Variant(value));  
  348.     }  
  349.   
  350.    
  351.    
  352.    
  353.     /** 
  354.      * Insert label Name in word as label name and label Value as label value 
  355.      * @param labelName 
  356.      * @param labelValue 
  357.      */  
  358.     public  void insertLabelValue(String labelName,String labelValue) {  
  359.   
  360.        Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();  
  361.        boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();  
  362.         if (isExist == true) {  
  363.             Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", labelName).toDispatch();  
  364.             Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();  
  365.             String bookMark1Value = Dispatch.get(range1, "Text").toString();  
  366.             System.out.println("Bookmark content:"+bookMark1Value);  
  367.         } else {  
  368.             System.out.println("Current bookmarks do not exist,Re establishment!");  
  369.             //TODO inserts text first, then finds the selected Chinese text, and then inserts labels.  
  370.             this.insertText(labelValue);  
  371. //This. find (label Value); // Find text, and select  
  372.             this.setFont(truetrue,true,"102,92,38""20""",true);  
  373.             Dispatch.call(bookMarks, "Add", labelName, selection);  
  374.             Dispatch.call(bookMarks, "Hidden", labelName);  
  375.         }  
  376.     }  
  377.     /** 
  378.      * Insert label Name in word as label name 
  379.      * @param labelName 
  380.      */  
  381.     public  void insertLabel(String labelName) {  
  382.   
  383.        Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();  
  384.        boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();  
  385.         if (isExist == true) {  
  386.             System.out.println("Bookmarks already exist");  
  387.         } else {  
  388.             System.out.println("Establish bookmarks:"+labelName);  
  389.             Dispatch.call(bookMarks, "Add", labelName, selection);  
  390.         }  
  391.     }     
  392.     /** 
  393.      * Search bookmarks 
  394.      * @param labelName 
  395.      * @return 
  396.      */  
  397.     public boolean findLabel(String labelName) {  
  398.        Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();  
  399.        boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();  
  400.        if (isExist == true) {  
  401.             return true;  
  402.         } else {  
  403.             System.out.println("Current bookmarks do not exist!");  
  404.             return false;  
  405.         }  
  406.     }  
  407.     /** 
  408.      * Fuzzy Search for Bookmarks and Return Accurate Bookmark Title 
  409.      * @param labelName 
  410.      * @return 
  411.      */  
  412.     public String findLabelLike(String labelName) {  
  413.        Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();  
  414.        int count = Dispatch.get(bookMarks, "Count").getInt(); //Bookmarks  
  415.        Dispatch rangeItem = null;  
  416.        String lname = "";  
  417.        for(int i=1;i<=count;i++){  
  418.            rangeItem = Dispatch.call(bookMarks, "Item"new Variant(i)).toDispatch();  
  419.            lname = Dispatch.call(rangeItem, "Name").toString();//bookmark name  
  420.            if(lname.startsWith(labelName)){//Front match  
  421. //return lname. replaceFirst (label Name, "); // return the following value  
  422.                return lname;  
  423.            }  
  424.        }  
  425.        return "";  
  426.     }  
  427.     /** 
  428.      * Fuzzy Delete Bookmarks 
  429.      * @param labelName 
  430.      */  
  431.     public void deleteLableLike(String labelName){  
  432.         Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();  
  433.        int count = Dispatch.get(bookMarks, "Count").getInt(); //Bookmarks  
  434.        Dispatch rangeItem = null;  
  435.        String lname = "";  
  436.        for(int i=1;i<=count;i++){  
  437.            rangeItem = Dispatch.call(bookMarks, "Item"new Variant(i)).toDispatch();  
  438.            lname = Dispatch.call(rangeItem, "Name").toString();//bookmark name  
  439.            if(lname.startsWith(labelName)){//Front match  
  440.                Dispatch.call(rangeItem, "Delete");  
  441.                count--;//Bookmarks have been deleted, the number of bookmarks and the current number of bookmarks should be reduced by 1, otherwise the error will be reported: the collection can not be found.  
  442.                i--;  
  443.            }  
  444.        }  
  445.     }  
  446.     /** 
  447.      * Getting Bookmark Content 
  448.      * @param labelName 
  449.      * @return 
  450.      */  
  451.     public String getLableValue(String labelName){  
  452.         if(this.findLabel(labelName)){  
  453.             Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();  
  454.             Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", labelName).toDispatch();  
  455.             Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();  
  456.             Dispatch font = Dispatch.get(range1, "Font").toDispatch();  
  457.             Dispatch.put(font, "Hidden"new Variant(false)); //Display bookmark content  
  458.             String bookMark1Value = Dispatch.get(range1, "Text").toString();  
  459.             System.out.println("Bookmark content:"+bookMark1Value);  
  460. //            font = Dispatch.get(range1, "Font").toDispatch();  
  461. //Dispatch.put(font,'Hidden', new Variant (true); //Hide bookmark content  
  462.             return bookMark1Value;  
  463.         }  
  464.         return "";  
  465.     }  
  466.   
  467.    
  468.     public static void main(String[] args) throws Exception {  
  469.   
  470.     }     
  471.    
  472. }  

When using jacob mode to operate documents, the phenomenon of card machine often appears, so poi mode is used to operate bookmarks at last. If the simple operation of bookmarks using poi mode is relatively simple, but to operate tables, document formats and so on or using jacob function is more powerful.

Posted by kagedwebdesign on Fri, 19 Apr 2019 10:21:34 -0700