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
- ActiveXComponent word = null;
- try {
- word = new ActiveXComponent("Word.Application");
- System.out.println("jacob Current version:"+word.getBuildVersion());
- }catch(Exception e ){
- e.printStackTrace();
- }
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.
- import java.io.File;
- import java.util.HashMap;
- import java.util.Map;
- import com.gdcn.bpaf.common.helper.StringHelper;
- import com.jacob.activeX.ActiveXComponent;
- import com.jacob.com.ComThread;
- import com.jacob.com.Dispatch;
- import com.jacob.com.Variant;
- /**
- * *
- * <p>Description: {jacob Operating word class}</p>
- *
- * <p>Copyright: Copyright (c) 2011</p>
- *
- * <p>CreateDate: 2012-6-28</p>
- *
- * @author Beny
- * @version 1.0
- */
- public class JacobHelper {
- //word document
- private Dispatch doc;
- //word Running Program Object
- private ActiveXComponent word;
- //All word document collections
- private Dispatch documents;
- //Selected range or insertion point
- private Dispatch selection;
- private boolean saveOnExit = true;
- public JacobHelper(boolean visible) throws Exception {
- ComThread.InitSTA();//Thread start
- if (word == null) {
- word = new ActiveXComponent("Word.Application");
- word.setProperty("Visible", new Variant(visible)); //Open word invisibly
- word.setProperty("AutomationSecurity", new Variant(3)); //Forbidden macro
- }
- if (documents == null)
- documents = word.getProperty("Documents").toDispatch();
- }
- /**
- * Setting exit parameters
- *
- * @param saveOnExit
- * boolean true-Save the file when you quit, false - do not save the file when you quit
- */
- public void setSaveOnExit(boolean saveOnExit) {
- this.saveOnExit = saveOnExit;
- }
- /**
- * Create a new word document
- *
- */
- public void createNewDocument() {
- doc = Dispatch.call(documents, "Add").toDispatch();
- selection = Dispatch.get(word, "Selection").toDispatch();
- }
- /**
- * Open an existing document
- *
- * @param docPath
- */
- public void openDocument(String docPath) {
- // closeDocument();
- doc = Dispatch.call(documents, "Open", docPath).toDispatch();
- selection = Dispatch.get(word, "Selection").toDispatch();
- }
- /**
- * Open an encrypted document in read-only mode
- *
- * @param docPath-Full name of file
- * @param pwd-Password
- */
- public void openDocumentOnlyRead(String docPath, String pwd)
- throws Exception {
- // closeDocument();
- doc = Dispatch.callN(
- documents,
- "Open",
- new Object[] { docPath, new Variant(false), new Variant(true),
- new Variant(true), pwd, "", new Variant(false) })
- .toDispatch();
- selection = Dispatch.get(word, "Selection").toDispatch();
- }
- /**
- * Open an encrypted document
- * @param docPath
- * @param pwd
- * @throws Exception
- */
- public void openDocument(String docPath, String pwd) throws Exception {
- // closeDocument();
- doc = Dispatch.callN(
- documents,
- "Open",
- new Object[] { docPath, new Variant(false), new Variant(false),
- new Variant(true), pwd }).toDispatch();
- selection = Dispatch.get(word, "Selection").toDispatch();
- }
- /**
- * Find text from the selected content or insertion point
- *
- * @param toFindText
- * Text to look for
- * @return boolean true-Find and select the text, false - No text found
- */
- @SuppressWarnings("static-access")
- public boolean find(String toFindText) {
- if (toFindText == null || toFindText.equals(""))
- return false;
- //Start with the location of selection
- Dispatch find = word.call(selection, "Find").toDispatch();
- //Setting up what to look for
- Dispatch.put(find, "Text", toFindText);
- //Look forward
- Dispatch.put(find, "Forward", "True");
- //Format
- Dispatch.put(find, "Format", "True");
- //Case matching
- Dispatch.put(find, "MatchCase", "True");
- //Full-word matching
- Dispatch.put(find, "MatchWholeWord", "false");
- //Find and select
- return Dispatch.call(find, "Execute").getBoolean();
- }
- /**
- * Set the selected content to replace text
- *
- * @param toFindText
- * Find strings
- * @param newText
- * Contents to be replaced
- * @return
- */
- public boolean replaceText(String toFindText, String newText) {
- if (!find(toFindText))
- return false;
- Dispatch.put(selection, "Text", newText);
- return true;
- }
- /**
- * Global Replacement Text
- *
- * @param toFindText
- * Find strings
- * @param newText
- * Contents to be replaced
- */
- public void replaceAllText(String toFindText, String newText) {
- while (find(toFindText)) {
- Dispatch.put(selection, "Text", newText);
- Dispatch.call(selection, "MoveRight");
- }
- }
- /**
- * Insert a string at the current insertion point
- *
- * @param newText
- * New string to insert
- */
- public void insertText(String newText) {
- Dispatch.put(selection, "Text", newText);
- }
- /**
- * Set the font for the current selection
- *
- * @param boldSize
- * @param italicSize
- * @param underLineSize
- * Underline
- * @param colorSize
- * Font color
- * @param size
- * font size
- * @param name
- * Font name
- * @param hidden
- * Is it hidden?
- */
- public void setFont(boolean bold, boolean italic, boolean underLine,
- String colorSize, String size, String name,boolean hidden) {
- Dispatch font = Dispatch.get(selection, "Font").toDispatch();
- Dispatch.put(font, "Name", new Variant(name));
- Dispatch.put(font, "Bold", new Variant(bold));
- Dispatch.put(font, "Italic", new Variant(italic));
- Dispatch.put(font, "Underline", new Variant(underLine));
- Dispatch.put(font, "Color", colorSize);
- Dispatch.put(font, "Size", size);
- Dispatch.put(font, "Hidden", hidden);
- }
- /**
- * Files are saved or saved as
- *
- * @param savePath
- * Save or save as a path
- */
- public void save(String savePath) {
- Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
- "FileSaveAs", savePath);
- }
- /**
- * Files are saved in html format
- *
- * @param savePath
- * @param htmlPath
- */
- public void saveAsHtml(String htmlPath) {
- Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
- htmlPath, new Variant(8) }, new int[1]);
- }
- /**
- * close document
- *
- * @param val
- * 0 Do not save modifications - 1. Save modifications - 2. Indicate whether to save modifications
- */
- public void closeDocument(int val) {
- Dispatch.call(doc, "Close", new Variant(val));//Note: Douments, not doc s
- documents = null;
- doc = null;
- }
- /**
- * Close the current word document
- *
- */
- public void closeDocument() {
- if (documents != null) {
- Dispatch.call(documents, "Save");
- Dispatch.call(documents, "Close", new Variant(saveOnExit));
- documents = null;
- doc = null;
- }
- }
- public void closeDocumentWithoutSave() {
- if (documents != null) {
- Dispatch.call(documents, "Close", new Variant(false));
- documents = null;
- doc = null;
- }
- }
- /**
- * Save and close all applications
- *
- */
- public void close() {
- closeDocument(-1);
- if (word != null) {
- // Dispatch.call(word, "Quit");
- word.invoke("Quit", new Variant[] {});
- word = null;
- }
- selection = null;
- documents = null;
- ComThread.Release();//Release the com thread. According to jacob's help document, thread recycling at com is not handled by java's garbage collector
- }
- /**
- * Print the current word document
- *
- */
- public void printFile() {
- if (doc != null) {
- Dispatch.call(doc, "PrintOut");
- }
- }
- /**
- * Protect the current file, if it does not exist, use expression.Protect(Type, NoReset, Password)
- *
- * @param pwd
- * @param type
- * WdProtectionType One of the constants (int type, read-only):
- * 1-wdAllowOnlyComments Endorsement only
- * 2-wdAllowOnlyFormFields Fill in the form only
- * 0-wdAllowOnlyRevisions Revision only
- * -1-wdNoProtection No protection.
- * 3-wdAllowOnlyReading read-only
- *
- */
- public void protectedWord(String pwd,String type) {
- String protectionType = Dispatch.get(doc, "ProtectionType").toString();
- if (protectionType.equals("-1")) {
- Dispatch.call(doc, "Protect", Integer.parseInt(type), new Variant(true),pwd);
- }
- }
- /**
- * Remove document protection if it exists
- *
- * @param pwd
- * WdProtectionType One of the constants (int type, read-only):
- * 1-wdAllowOnlyComments Endorsement only
- * 2-wdAllowOnlyFormFields Fill in the form only
- * 0-wdAllowOnlyRevisions Revision only
- * -1-wdNoProtection No protection.
- * 3-wdAllowOnlyReading read-only
- *
- */
- public void unProtectedWord(String pwd) {
- String protectionType = Dispatch.get(doc, "ProtectionType").toString();
- if (!protectionType.equals("0")&&!protectionType.equals("-1")) {
- Dispatch.call(doc, "Unprotect", pwd);
- }
- }
- /**
- * Protection Type of Return Document
- * @return
- */
- public String getProtectedType(){
- return Dispatch.get(doc, "ProtectionType").toString();
- }
- /**
- * Setting word Document Security Level
- *
- * @param value
- * 1-msoAutomationSecurityByUI Use the security settings specified in the Security dialog box.
- * 2-msoAutomationSecurityForceDisable
- * Disable all macros in all files opened by the program without showing any security alerts. 3-mso Automation Security Low
- * Enable all macros, which is the default when starting the application.
- */
- public void setAutomationSecurity(int value) {
- word.setProperty("AutomationSecurity", new Variant(value));
- }
- /**
- * Insert label Name in word as label name and label Value as label value
- * @param labelName
- * @param labelValue
- */
- public void insertLabelValue(String labelName,String labelValue) {
- Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
- boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();
- if (isExist == true) {
- Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", labelName).toDispatch();
- Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
- String bookMark1Value = Dispatch.get(range1, "Text").toString();
- System.out.println("Bookmark content:"+bookMark1Value);
- } else {
- System.out.println("Current bookmarks do not exist,Re establishment!");
- //TODO inserts text first, then finds the selected Chinese text, and then inserts labels.
- this.insertText(labelValue);
- //This. find (label Value); // Find text, and select
- this.setFont(true, true,true,"102,92,38", "20", "",true);
- Dispatch.call(bookMarks, "Add", labelName, selection);
- Dispatch.call(bookMarks, "Hidden", labelName);
- }
- }
- /**
- * Insert label Name in word as label name
- * @param labelName
- */
- public void insertLabel(String labelName) {
- Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
- boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();
- if (isExist == true) {
- System.out.println("Bookmarks already exist");
- } else {
- System.out.println("Establish bookmarks:"+labelName);
- Dispatch.call(bookMarks, "Add", labelName, selection);
- }
- }
- /**
- * Search bookmarks
- * @param labelName
- * @return
- */
- public boolean findLabel(String labelName) {
- Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
- boolean isExist = Dispatch.call(bookMarks, "Exists", labelName).getBoolean();
- if (isExist == true) {
- return true;
- } else {
- System.out.println("Current bookmarks do not exist!");
- return false;
- }
- }
- /**
- * Fuzzy Search for Bookmarks and Return Accurate Bookmark Title
- * @param labelName
- * @return
- */
- public String findLabelLike(String labelName) {
- Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
- int count = Dispatch.get(bookMarks, "Count").getInt(); //Bookmarks
- Dispatch rangeItem = null;
- String lname = "";
- for(int i=1;i<=count;i++){
- rangeItem = Dispatch.call(bookMarks, "Item", new Variant(i)).toDispatch();
- lname = Dispatch.call(rangeItem, "Name").toString();//bookmark name
- if(lname.startsWith(labelName)){//Front match
- //return lname. replaceFirst (label Name, "); // return the following value
- return lname;
- }
- }
- return "";
- }
- /**
- * Fuzzy Delete Bookmarks
- * @param labelName
- */
- public void deleteLableLike(String labelName){
- Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
- int count = Dispatch.get(bookMarks, "Count").getInt(); //Bookmarks
- Dispatch rangeItem = null;
- String lname = "";
- for(int i=1;i<=count;i++){
- rangeItem = Dispatch.call(bookMarks, "Item", new Variant(i)).toDispatch();
- lname = Dispatch.call(rangeItem, "Name").toString();//bookmark name
- if(lname.startsWith(labelName)){//Front match
- Dispatch.call(rangeItem, "Delete");
- 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.
- i--;
- }
- }
- }
- /**
- * Getting Bookmark Content
- * @param labelName
- * @return
- */
- public String getLableValue(String labelName){
- if(this.findLabel(labelName)){
- Dispatch bookMarks = Dispatch.call(doc, "Bookmarks").toDispatch();
- Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", labelName).toDispatch();
- Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
- Dispatch font = Dispatch.get(range1, "Font").toDispatch();
- Dispatch.put(font, "Hidden", new Variant(false)); //Display bookmark content
- String bookMark1Value = Dispatch.get(range1, "Text").toString();
- System.out.println("Bookmark content:"+bookMark1Value);
- // font = Dispatch.get(range1, "Font").toDispatch();
- //Dispatch.put(font,'Hidden', new Variant (true); //Hide bookmark content
- return bookMark1Value;
- }
- return "";
- }
- public static void main(String[] args) throws Exception {
- }
- }
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.