Java USES the Jsoup component to generate a word document

  • 2020-04-01 02:27:44
  • OfStack

To use jsoup first will get the HTML code "standardised" (jsoup. Parse (String HTML)) method, and then use FileWiter write the HTML content to the local template. The doc file, at this time if the articles contained in the pictures, the template. The doc will depend on your local image file path, if you change the picture or change the path of a name, then open the template. The doc, will no longer display images (a fork fork). To solve this problem, the jsoup component is used to loop through the content of the HTML document, replace the img element with the identity of ${image_ self-increment}, take out the SRC attribute in the img element, and store it in the form of key-value pairs, for example:


Map<Integer,String> imgMap = new HashMap<Integer,String>();
imgMap.put(1, " D:lucene.png " );
 


At this point your HTML content will look like this :(for example)

<html>
 <head></head>
 <body>

  <p> Test message 1</p>
  <p>${image_1}<p>
  <table>
   <tr>
    <td> <td>
   </tr>
  </table>
  <p> Test message 2</p>
  <a href=//www.jb51.net><p>${image_2}</p></a>
  <p> Test message 3</p>
 </body>
</html>

After saving to the local file, open your saved template.doc with the MSOfficeGeneratorUtils class (see the tool class below, based on the open source component Jacob), call replaceText2Image, and replace the image id in the above code with an image, thus eliminating the problem of the local image path. Then call the copy method to copy the entire document, close the template.doc file, create a new doc file, and call the paste method to paste the contents of the template.doc you just copied. That's pretty much it.
There is also an implicit problem with copying the entire word document. That is, when you copy too much, close the word program and a dialog box will appear asking you if you can apply the copied data to other programs. The solution to this problem is very simple. You can create a new document, type a line, and then call the copy method before calling quit, which will not prompt you when you close the word program. See the following code
// copy a *.doc document with less content, to prevent the prompt that there is a large amount of copy content in memory when closing word program, whether to apply to other programs dialog box,

msOfficeUtils.createNewDocument();
msOfficeUtils.insertText(" Test message ");
msOfficeUtils.copy();
msOfficeUtils.close();
msOfficeUtils.quit();
Jacob in sourceforge The links on the 
Jsoup website 
MsOfficeGeneratorUtils
package com.topstar.test;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class MSOfficeGeneratorUtils {
 
 private ActiveXComponent word = null;
 
 private Dispatch document = null;
 
 private Dispatch documents = null;
 /**
  * selection  Represents the selection in the currently active document window. If nothing is selected in the document, this object represents the insertion point (where the cursor is). <br/>
  *  Only one document window can exist selection Object, and there can be only one active one in the entire application selection object 
  */
 private Dispatch selection = null;
 /**
  * range  The object represents a contiguous area of the document. each range An object is defined by a starting and ending character position. <br/>
  * range  Object is independent of the selected content. You can define and work with a scope without changing the selection. You can also define multiple scopes in the document. But you can only have one selected content in each document 
  */
 private Dispatch range = null;
 
 private Dispatch pageSetup = null;
 
 private Dispatch tables = null;
 
 private Dispatch table = null;
 
 private Dispatch rows = null;
 
 private Dispatch cols = null;
 
 private Dispatch row = null;
 
 private Dispatch col = null;
 
 private Dispatch cell = null;
 
 private Dispatch font = null;
 
 private Dispatch alignment = null;
 
 public MSOfficeGeneratorUtils(boolean visible) {
  if (this.word == null) {
   //Initializes an instance of Microsoft Office Word
   this.word = new ActiveXComponent("Word.Application");
   this.word.setProperty("Visible", new Variant(visible));
   //Disable macros
   this.word.setProperty("AutomationSecurity", new Variant(3));
  }
  if (this.documents == null)
   this.documents = word.getProperty("Documents").toDispatch();
 }
 /**
  *  Sets the page direction and margins 
  * 
  * @param orientation
  *             Page orientation 
  *            <ul>
  *            <li>0  The transverse </li>
  *            <li>1  The longitudinal </li>
  *            </ul>
  * @param leftMargin
  *             The left margin 
  * @param rightMargin
  *             The right margin 
  * @param topMargin
  *             From the above 
  * @param buttomMargin
  *             Bottom margin 
  */
 public void setPageSetup(int orientation, int leftMargin, int rightMargin,
   int topMargin, int buttomMargin) {
  if (this.pageSetup == null)
   this.getPageSetup();
  Dispatch.put(pageSetup, "Orientation", orientation);
  Dispatch.put(pageSetup, "LeftMargin", leftMargin);
  Dispatch.put(pageSetup, "RightMargin", rightMargin);
  Dispatch.put(pageSetup, "TopMargin", topMargin);
  Dispatch.put(pageSetup, "BottomMargin", buttomMargin);
 }
 
 public Dispatch openDocument(String docPath) {
  this.document = Dispatch.call(documents, "Open", docPath).toDispatch();
  this.getSelection();
  this.getRange();
  this.getAlignment();
  this.getFont();
  this.getPageSetup();
  return this.document;
 }
 
 public Dispatch createNewDocument() {
  this.document = Dispatch.call(documents, "Add").toDispatch();
  this.getSelection();
  this.getRange();
  this.getPageSetup();
  this.getAlignment();
  this.getFont();
  return this.document;
 }
 
 public Dispatch getSelection() {
  this.selection = word.getProperty("Selection").toDispatch();
  return this.selection;
 }
 
 public Dispatch getRange() {
  this.range = Dispatch.get(this.selection, "Range").toDispatch();
  return this.range;
 }
 
 public Dispatch getPageSetup() {
  if (this.document == null)
   return this.pageSetup;
  this.pageSetup = Dispatch.get(this.document, "PageSetup").toDispatch();
  return this.pageSetup;
 }
 
 public void moveUp(int count) {
  for (int i = 0; i < count; i++)
   Dispatch.call(this.selection, "MoveUp");
 }
 
 public void moveDown(int count) {
  for (int i = 0; i < count; i++)
   Dispatch.call(this.selection, "MoveDown");
 }
 
 public void moveLeft(int count) {
  for (int i = 0; i < count; i++)
   Dispatch.call(this.selection, "MoveLeft");
 }
 
 public void moveRight(int count) {
  for (int i = 0; i < count; i++)
   Dispatch.call(this.selection, "MoveRight");
 }
 
 public void enterDown(int count) {
  for (int i = 0; i < count; i++)
   Dispatch.call(this.selection, "TypeParagraph");
 }
 
 public void moveStart() {
  Dispatch.call(this.selection, "HomeKey", new Variant(6));
 }
 
 public void moveEnd() {
  Dispatch.call(selection, "EndKey", new Variant(6));
 }

 
 
 public boolean find(String toFindText) {
  //Start the query at the location of selection
  Dispatch find = Dispatch.call(this.selection, "Find").toDispatch();
  //Set what to look for? Hot? Br />     Dispatch. The put (the find, "Text", toFindText);
  //Look ahead
  Dispatch.put(find, "Forward", "True");
  //Set the format
  Dispatch.put(find, "Format", "True");
  //Case matching
  Dispatch.put(find, "MatchCase", "True");
  //Full word matching
  Dispatch.put(find, "MatchWholeWord", "True");
  //Find and select
  return Dispatch.call(find, "Execute").getBoolean();
 }
 
 public void replace(String newText) {
  //Set the replacement text
  Dispatch.put(this.selection, "Text", newText);
 }
 
 public void replaceAll(String oldText, Object replaceObj) {
  //Moves the insertion point to the beginning of the file
  moveStart();
  //Table replacement
  String newText = (String) replaceObj;
  //Picture replacement method
  if (oldText.indexOf("image") != -1 || newText.lastIndexOf(".bmp") != -1 || newText.lastIndexOf(".jpg") != -1 || newText.lastIndexOf(".gif") != -1) {
   while (find(oldText)) {
    insertImage(newText);
    Dispatch.call(this.selection, "MoveRight");
   }
   //text
  } else {
   while (find(oldText)) {
    replace(newText);
    Dispatch.call(this.selection, "MoveRight");
   }
  }
 }

 
 public void replaceText2Image(String replaceText,String imgPath){
  moveStart();
  while(find(replaceText)){
   insertImage(imgPath);
   moveEnd();
   enterDown(1);
  }
 }
 
 public void insertImage(String imagePath) {
  Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(), "AddPicture", imagePath);
 }
 
 public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,
   int secCellRowIdx, int secCellColIdx) {
  getTable(tableIndex);
  Dispatch fstCell = Dispatch.call(table, "Cell",
    new Variant(fstCellRowIdx), new Variant(fstCellColIdx))
    .toDispatch();
  Dispatch secCell = Dispatch.call(table, "Cell",
    new Variant(secCellRowIdx), new Variant(secCellColIdx))
    .toDispatch();
  Dispatch.call(fstCell, "Merge", secCell);
 }
 
 public void splitCell(int numRows, int numColumns) {
  Dispatch.call(this.cell, "Split", new Variant(numRows), new Variant(
    numColumns));
 }
 /**
  *  Writes to a table 
  * 
  * @param list
  *             What to write <br/>
  *             Note: list.size()  Should be with the table rows Consistent, String An array of length Attributes should be associated with the table columns consistent 
  */
 public void insertToTable(List<String[]> list) {
  if (list == null || list.size() <= 0)
   return;
  if (this.table == null)
   return;
  for (int i = 0; i < list.size(); i++) {
   String[] strs = list.get(i);
   for (int j = 0; j < strs.length; j++) {
    //Go through each?? In the table. Cell, how many times do I have to fill in? Hot Fu? Ken before? Br />         Dispatch cell = this.getcell (I + 1, j + 1);
    //Select this cell
    Dispatch.call(cell, "Select");
    //Write? Hot health  ピ  sauce say? 1? Br />         Dispatch. The put (enclosing selection, "Text", the STRS [j]);
    //Move the insertion point to the next?? location
   }
   this.moveDown(1);
  }
  //A newline
  this.enterDown(1);
 }
 
 public void insertToDocument(List<String> list) {
  if (list == null || list.size() <= 0)
   return;
  if (this.document == null)
   return;
  for (String str : list) {
   Dispatch.put(this.selection, "Text", str);
   this.moveDown(1);
   this.enterDown(1);
  }
 }
 
 public void insertToText(String insertText) {
  Dispatch.put(this.selection, "Text", insertText);
 }
 
 public void insertText(String newText) {
  Dispatch.put(selection, "Text", newText);
 }
 /**
  *  Create a new table 
  * 
  * @param rowCount
  *             line 
  * @param colCount
  *             column 
  * @param width
  *             Table borders 
  *            <ul>
  *            <li>0  No border </li>
  *            <li>1  Have a border </li>
  *            </ul>
  * @return  Table object 
  */
 public Dispatch createNewTable(int rowCount, int colCount, int width) {
  if (this.tables == null)
   this.getTables();
  this.getRange();
  if (rowCount > 0 && colCount > 0)
   this.table = Dispatch.call(this.tables, "Add", this.range,
     new Variant(rowCount), new Variant(colCount),
     new Variant(width)).toDispatch();
  return this.table;
 }
 
 public Dispatch getTables() {
  if (this.document == null)
   return this.tables;
  this.tables = Dispatch.get(this.document, "Tables").toDispatch();
  return this.tables;
 }
 
 public int getTablesCount() {
  if (this.tables == null)
   this.getTables();
  return Dispatch.get(tables, "Count").getInt();
 }
 
 public Dispatch getTable(int tableIndex) {
  if (this.tables == null)
   this.getTables();
  if (tableIndex >= 0)
   this.table = Dispatch.call(this.tables, "Item", new Variant(tableIndex)).toDispatch();
  return this.table;
 }
 
 public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx, String txt) {
  getTable(tableIndex);
  getCell(cellRowIdx, cellColIdx);
  Dispatch.call(this.cell, "Select");
  Dispatch.put(this.selection, "Text", txt);
 }
 
 public void copyParagraphFromAnotherDoc(String anotherDocPath, int paragraphIndex) {
  Dispatch wordContent = Dispatch.get(this.document, "Content").toDispatch(); //Gets the contents of the current document
  Dispatch.call(wordContent, "InsertAfter", "$selection$");//The insert special character locates the insertion point
  copyParagraphFromAnotherDoc(anotherDocPath, paragraphIndex, "$selection$");
 }
 
 public void copyParagraphFromAnotherDoc(String anotherDocPath, int paragraphIndex, String pos) {
  Dispatch doc2 = null;
  try {
   doc2 = Dispatch.call(documents, "Open", anotherDocPath).toDispatch();
   Dispatch paragraphs = Dispatch.get(doc2, "Paragraphs").toDispatch();
   Dispatch paragraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphIndex)).toDispatch();
   Dispatch range = Dispatch.get(paragraph, "Range").toDispatch();
   Dispatch.call(range, "Copy");
   if (this.find(pos)) {
    getRange();
    Dispatch.call(this.range, "Paste");
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (doc2 != null) {
    Dispatch.call(doc2, "Close", new Variant(true));
    doc2 = null;
   }
  }
 }
 
 public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex,
   String pos) {
  Dispatch doc2 = null;
  try {
   doc2 = Dispatch.call(documents, "Open", anotherDocPath)
     .toDispatch();
   Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();
   Dispatch table = Dispatch.call(tables, "Item",
     new Variant(tableIndex)).toDispatch();
   Dispatch range = Dispatch.get(table, "Range").toDispatch();
   Dispatch.call(range, "Copy");
   if (this.find(pos)) {
    getRange();
    Dispatch.call(this.range, "Paste");
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (doc2 != null) {
    Dispatch.call(doc2, "Close", new Variant(true));
    doc2 = null;
   }
  }
 }
 
 public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex,
   String pos) {
  Dispatch doc2 = null;
  try {
   doc2 = Dispatch.call(documents, "Open", anotherDocPath)
     .toDispatch();
   Dispatch shapes = Dispatch.get(doc2, "InLineShapes").toDispatch();
   Dispatch shape = Dispatch.call(shapes, "Item",
     new Variant(shapeIndex)).toDispatch();
   Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch();
   Dispatch.call(imageRange, "Copy");
   if (this.find(pos)) {
    getRange();
    Dispatch.call(this.range, "Paste");
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (doc2 != null) {
    Dispatch.call(doc2, "Close", new Variant(true));
    doc2 = null;
   }
  }
 }
 
 public void addTableRow(int tableIndex, int rowIndex) {
  getTable(tableIndex);
  getTableRows();
  getTableRow(rowIndex);
  Dispatch.call(this.rows, "Add", new Variant(this.row));
 }
 
 public void addFirstTableRow(int tableIndex) {
  getTable(tableIndex);
  getTableRows();
  Dispatch row = Dispatch.get(rows, "First").toDispatch();
  Dispatch.call(this.rows, "Add", new Variant(row));
 }
 
 public void addLastTableRow(int tableIndex) {
  getTable(tableIndex);
  getTableRows();
  Dispatch row = Dispatch.get(this.rows, "Last").toDispatch();
  Dispatch.call(this.rows, "Add", new Variant(row));
 }
 
 public void addRow(int tableIndex) {
  getTable(tableIndex);
  getTableRows();
  Dispatch.call(this.rows, "Add");
 }
 
 public void addCol(int tableIndex) {
  getTable(tableIndex);
  getTableColumns();
  Dispatch.call(this.cols, "Add").toDispatch();
  Dispatch.call(this.cols, "AutoFit");
 }
 
 public void addTableCol(int tableIndex, int colIndex) {
  getTable(tableIndex);
  getTableColumns();
  getTableColumn(colIndex);
  Dispatch.call(this.cols, "Add", this.col).toDispatch();
  Dispatch.call(this.cols, "AutoFit");
 }
 
 public void addFirstTableCol(int tableIndex) {
  getTable(tableIndex);
  Dispatch cols = getTableColumns();
  Dispatch col = Dispatch.get(cols, "First").toDispatch();
  Dispatch.call(cols, "Add", col).toDispatch();
  Dispatch.call(cols, "AutoFit");
 }
 
 public void addLastTableCol(int tableIndex) {
  getTable(tableIndex);
  Dispatch cols = getTableColumns();
  Dispatch col = Dispatch.get(cols, "Last").toDispatch();
  Dispatch.call(cols, "Add", col).toDispatch();
  Dispatch.call(cols, "AutoFit");
 }
 
 public int getTableColumnsCount() {
  if (this.table == null)
   return 0;
  return Dispatch.get(this.cols, "Count").getInt();
 }
 
 public int getTableRowsCount() {
  if (this.table == null)
   return 0;
  return Dispatch.get(this.rows, "Count").getInt();
 }
 
 public Dispatch getTableColumns() {
  if (this.table == null)
   return this.cols;
  this.cols = Dispatch.get(this.table, "Columns").toDispatch();
  return this.cols;
 }
 
 public Dispatch getTableRows() {
  if (this.table == null)
   return this.rows;
  this.rows = Dispatch.get(this.table, "Rows").toDispatch();
  return this.rows;
 }
 
 public Dispatch getTableColumn(int columnIndex) {
  if (this.cols == null)
   this.getTableColumns();
  if (columnIndex >= 0)
   this.col = Dispatch.call(this.cols, "Item",
     new Variant(columnIndex)).toDispatch();
  return this.col;
 }
 
 public Dispatch getTableRow(int rowIndex) {
  if (this.rows == null)
   this.getTableRows();
  if (rowIndex >= 0)
   this.row = Dispatch.call(this.rows, "Item", new Variant(rowIndex))
     .toDispatch();
  return this.row;
 }
 
 public void autoFitTable() {
  int count = this.getTablesCount();
  for (int i = 0; i < count; i++) {
   Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
     .toDispatch();
   Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
   Dispatch.call(cols, "AutoFit");
  }
 }
 
 public Dispatch getCell(int cellRowIdx, int cellColIdx) {
  if (this.table == null)
   return this.cell;
  if (cellRowIdx >= 0 && cellColIdx >= 0)
   this.cell = Dispatch.call(this.table, "Cell",
     new Variant(cellRowIdx), new Variant(cellColIdx))
     .toDispatch();
  return this.cell;
 }
 public void selectCell(int cellRowIdx, int cellColIdx) {
  if (this.table == null)
   return;
  getCell(cellRowIdx, cellColIdx);
  if (cellRowIdx >= 0 && cellColIdx >= 0)
   Dispatch.call(this.cell, "select");
 }
 
 public void setTitle(String title, int alignmentType) {
  if (title == null || "".equals(title))
   return;
  if (this.alignment == null)
   this.getAlignment();
  if(alignmentType != 0 && alignmentType != 1 && alignmentType != 2)
   alignmentType = 0;
  Dispatch.put(this.alignment, "Alignment", alignmentType);
  Dispatch.call(this.selection, "TypeText", title);
 }
 /**
  *  Sets the thickness of the current table border 
  * 
  * @param width
  *             Scope: 1 < w < 13 .   If it is 0 , on behalf of ?] A box <br/>
  */
 public void setTableBorderWidth(int width) {
  if (this.table == null)
   return;
  
  Dispatch borders = Dispatch.get(table, "Borders").toDispatch();
  Dispatch border = null;
  for (int i = 1; i < 7; i++) {
   border = Dispatch.call(borders, "Item", new Variant(i))
     .toDispatch();
   if (width != 0) {
    Dispatch.put(border, "LineWidth", new Variant(width));
    Dispatch.put(border, "Visible", new Variant(true));
   } else if (width == 0) {
    Dispatch.put(border, "Visible", new Variant(false));
   }
  }
 }
 
 public String getTxtFromCell(int tableIndex, int rowIndex, int colIndex) {
  String value = "";
  //Set to the current table
  getTable(tableIndex);
  getCell(rowIndex, colIndex);
  if (cell != null) {
   Dispatch.call(cell, "Select");
   value = Dispatch.get(selection, "Text").toString();
   value = value.substring(0, value.length() - 2); //Remove the last carriage return;
  }
  return value;
 }
 /**
  *  Sets bullets and lists for the currently selected content 
  * 
  * @param tabIndex
  *            <ul>
  *            <li>1. Item no. </li>
  *            <li>2. Serial number </li>
  *            <li>3. Multistage serial number </li>
  *            <li>4. A list of the style </li>
  *            </ul>
  * @param index
  *            0 It means no, and the other Numbers mean yes tab The number of items on the page 
  */
 public void applyListTemplate(int tabIndex, int index) {
  //Get a list of ListGalleries objects
  Dispatch listGalleries = Dispatch.get(this.word, "ListGalleries")
    .toDispatch();
  //Gets an object in the list
  Dispatch listGallery = Dispatch.call(listGalleries, "Item",
    new Variant(tabIndex)).toDispatch();
  Dispatch listTemplates = Dispatch.get(listGallery, "ListTemplates")
    .toDispatch();
  if (this.range == null)
   this.getRange();
  Dispatch listFormat = Dispatch.get(this.range, "ListFormat")
    .toDispatch();
  Dispatch.call(listFormat, "ApplyListTemplate",
    Dispatch.call(listTemplates, "Item", new Variant(index)),
    new Variant(true), new Variant(1), new Variant(0));
 }
 
 public void addTablesOfContents() {
  //Get the ActiveDocument, table of contents, range object
  Dispatch ActiveDocument = word.getProperty("ActiveDocument")
    .toDispatch();
  Dispatch TablesOfContents = Dispatch.get(ActiveDocument,
    "TablesOfContents").toDispatch();
  Dispatch range = Dispatch.get(this.selection, "Range").toDispatch();
  //Add directory
  Dispatch.call(TablesOfContents, "Add", range, new Variant(true),
    new Variant(1), new Variant(3), new Variant(true), new Variant(
      ""), new Variant(true), new Variant(true));
 }
 /**
  *  Set the current selection alignment 
  * 
  * @param alignmentType
  *            <ul>
  *            <li>0. The left </li>
  *            <li>1. In the middle </li>
  *            <li>2. In the right </li>
  *            </ul>
  */
 public void setAlignment(int alignmentType) {
  if (this.alignment == null)
   this.getAlignment();
  Dispatch.put(this.alignment, "Alignment", alignmentType);
 }
 
 public Dispatch getAlignment() {
  if (this.selection == null)
   this.getSelection();
  this.alignment = Dispatch.get(this.selection, "ParagraphFormat")
    .toDispatch();
  return this.alignment;
 }
 
 public Dispatch getFont() {
  if (this.selection == null)
   this.getSelection();
  this.font = Dispatch.get(this.selection, "Font").toDispatch();
  return this.font;
 }
 
 @Deprecated
 public void setFontScale(String fontName, boolean isBold, boolean isItalic,
   boolean isUnderline, String rgbColor, int Scale, int fontSize) {
  Dispatch.put(this.font, "Name", fontName);
  Dispatch.put(this.font, "Bold", isBold);
  Dispatch.put(this.font, "Italic", isItalic);
  Dispatch.put(this.font, "Underline", isUnderline);
  Dispatch.put(this.font, "Color", rgbColor);
  Dispatch.put(this.font, "Scaling", Scale);
  Dispatch.put(this.font, "Size", fontSize);
 }

 
  
 public void setFont(boolean isBold,boolean isItalic,boolean isUnderLine,String color,String size,String name) { 
    Dispatch font = Dispatch.get(getSelection(), "Font").toDispatch(); 
    Dispatch.put(font, "Name", new Variant(name)); 
    Dispatch.put(font, "Bold", new Variant(isBold)); 
    Dispatch.put(font, "Italic", new Variant(isItalic)); 
    Dispatch.put(font, "Underline", new Variant(isUnderLine)); 
    if(!"".equals(color))
     Dispatch.put(font, "Color", color); 
    Dispatch.put(font, "Size", size); 
 }
 
 public void saveAs(String outputPath) {
  if (this.document == null)
   return;
  if (outputPath == null || "".equals(outputPath))
   return;
  Dispatch.call(this.document, "SaveAs", outputPath);
 }
 
 public void saveAsHtml(String htmlFile) {
  Dispatch.invoke(this.document, "SaveAs", Dispatch.Method, new Object[] {
    htmlFile, new Variant(8) }, new int[1]);
 }
 
 
 public void close() {
  if (document == null)
   return;
  Dispatch.call(document, "Close", new Variant(0));
 }
 
 public void printFile() {
  if (document == null)
   return;
  Dispatch.call(document, "PrintOut");
 }
 
 public void quit() {
  word.invoke("Quit", new Variant[0]);
  ComThread.Release();
 }

 
 public void selectAllContent(){
  Dispatch.call(this.document,"select");
 }

 
 public void copy(){
  Dispatch.call(this.document,"select");
  Dispatch.call(this.selection,"copy");
 }

 
 public void paste(){
  Dispatch.call(this.selection,"paste");
 }

 public static void main(String[] args) throws IOException {
  MSOfficeGeneratorUtils officeUtils = new MSOfficeGeneratorUtils(true);
//  OfficeUtils. OpenDocument (" D:  TRS  TRSWCMV65HBTCIS  Tomcat  webapps  WCM  eipv65  briefreport  templates  zhengfa  head. Doc ");
//  officeUtils.replaceAll("${briefreport_year}", "2011");
//  officeUtils.replaceAll("${briefreport_issue}", "3");
//  File file = File.createTempFile("test", ".tmp");
//  System.out.println(file.getAbsolutePath());
//  file.delete();
//  File file = new File("C:DOCUME~1ADMINI~1LOCALS~1Temptest5411720146039914615.tmp");
//  System.out.println(file.exists());

  officeUtils.createNewDocument();
//  officeUtils.createNewTable(1, 1, 1);
//  Officeutils. insertText(" publish time :2011-11-11");
//  officeUtils.moveRight(1);
//  officeUtils.insertText("t");
//  officeUtils.moveRight(1);
//  Officeutils. insertText(" where channel: macro environment/social environment ");
//  officeUtils.moveRight(1);
//  officeUtils.insertText("t");
//  officeUtils.moveRight(1);
//  OfficeUtils. InsertText (" article author: Yang yemao ");
//  officeUtils.moveRight(1);
  officeUtils.insertText("I'm Chinese");
  officeUtils.moveRight(1);
  officeUtils.enterDown(1);
  officeUtils.insertText("I'm not Chinese");
  officeUtils.moveRight(1);

  


  //Officeutils. setFontScale (" Microsoft yahei ", true, true, true, "1,1,1", 100,
  // 18);
  // officeUtils.setAlignment(1);
  //Officeutils. insertToText(" this is a test ");
  // officeUtils.moveEnd();
  //Officeutils. setFontScale (" Microsoft yahi ", false, false, false, "1,1,1,1", 100,
  // 18);
  // officeUtils.insertImage("d:11.jpg");
  // officeUtils.enterDown(1);
  //Officeutils. insertToText(" here's my picture ");
  // officeUtils.enterDown(1);
  // officeUtils.createNewTable(3, 5, 1);
  // List<String[]> list = new ArrayList<String[]>();
  // for (int i = 0; i < 3; i++) {
  // String[] strs = new String[5];
  // for (int j = 0; j < 5; j++) {
  // strs[j] = j + i + "";
  // }
  // list.add(strs);
  // }
  // officeUtils.insertToTable(list);
  // officeUtils.createNewTable(10, 10, 1);
  // officeUtils.moveEnd();
  // officeUtils.enterDown(1);
  // officeUtils.createNewTable(3,2,1);
  // officeUtils.mergeCell(1, 1, 7, 1, 9);
  // officeUtils.mergeCell(1, 2, 2, 3, 7);
  // officeUtils.mergeCell(1, 3, 4, 9, 10);
  // officeUtils.insertText("123");
  // officeUtils.getCell(1, 2);
  // officeUtils.splitCell(2 , 4);
  // officeUtils.selectCell(1, 2);
  // officeUtils.insertText("split");
  // officeUtils.selectCell(1, 5);
  // officeUtils.insertText("split1");
  // officeUtils.selectCell(1, 6);
  // officeUtils.insertText("yy");
  // officeUtils.selectCell(2, 4);
  // officeUtils.insertText("ltg");
  // officeUtils.saveAs("D:" + System.currentTimeMillis() + ".doc");
//  officeUtils.close();
//  officeUtils.quit();
 }
}
 TestJsoupComponent
package com.topstar.test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import com.eprobiti.trs.TRSException;

public class TestJsoupComponent {
 private static Document document;
 private static Map<String, String> imgMap = new HashMap<String, String>(); //Image identifier and physical path i.e {"image_1","D:lucene.png"};
 private static List<String> files = new ArrayList<String>(); //Save the file names of each article doc locally generated
 private static Integer imgIndex = 1; //Photo id
 public static void main(String[] args) throws TRSException, IOException {
  MSOfficeGeneratorUtils officeUtils = new MSOfficeGeneratorUtils(true); //Make the build process invisible

  String html = "<html>.....</html>";//Get the body content and fill in the HTML content yourself here
  String header = " Test the title "; //Get the title of the article
  document = Jsoup.parse(html);
  // System.out.println(document.html());
  for (Element element : document.body().select("body > *"))
   //Recursively iterate through all direct child elements under the body, finding the img tag, @see SysElementText Method
   sysElementText(element);
  File file = new File("D:" + File.separator + "template.doc");
  file.createNewFile(); //Create template HTML
  FileWriter fw = new FileWriter(file);
  fw.write(document.html(), 0, document.html().length());//Written to the file
  fw.flush(); //Empty the FileWriter buffer
  fw.close();
  officeUtils.openDocument("D:template.doc"); //Open template.doc. The template.doc file generated by dochtmlcon in the trsserver eipdocument library
  officeUtils.copy(); //Copy the entire document
  officeUtils.close();
  officeUtils.createNewDocument();
  officeUtils.paste(); //Paste the entire document
  for (Entry<String, String> entry : imgMap.entrySet())   // Loop will Photo id Bits are replaced by pictures 
   officeUtils.replaceText2Image(entry.getKey(), entry.getValue());
  officeUtils.moveStart(); //Moves the insertion point to the apex of the Word document
  officeUtils.setFont(true, false, false, "0,0,0", "20", " Song typeface "); //Set the font, specific parameters, see their own API
  officeUtils.setTitle(header, 1); //Set the title
  officeUtils.enterDown(1); //Set a line return
  String filename = UUID.randomUUID().toString();
  files.add(filename); //Record file name,
  officeUtils.saveAs("D:" + File.separator + filename + ".doc"); //Generate D: uuid.doc file, using UUID to prevent the same name
  officeUtils.close(); //Close the document created by Office Word
  officeUtils.quit(); //Exit the Office Word program
  MSOfficeGeneratorUtils msOfficeUtils = new MSOfficeGeneratorUtils(false); //The integration process is set to visible
  msOfficeUtils.createNewDocument();
  msOfficeUtils.saveAs("D:" + File.separator + "complete.doc");
  msOfficeUtils.close();
  for (String fileName : files) {
   msOfficeUtils.openDocument("D:" + File.separator + fileName + ".doc");
   msOfficeUtils.copy();
   msOfficeUtils.close();
   msOfficeUtils.openDocument("D:" + File.separator + "complete.doc");
   msOfficeUtils.moveEnd();
   msOfficeUtils.enterDown(1);
   msOfficeUtils.paste();
   msOfficeUtils.saveAs("D:" + File.separator + "complete.doc");
   msOfficeUtils.close();
  }
  //Copy a *.doc document with less content to prevent the prompt that there is a large amount of copy content in memory when closing the word program, whether to apply to other programs dialog box,
  msOfficeUtils.createNewDocument();
  msOfficeUtils.insertText(" Test message ");
  msOfficeUtils.copy();
  msOfficeUtils.close();
  msOfficeUtils.quit();
  imgIndex = 1;
  imgMap.clear();
 }
 public static void sysElementText(Node node) {
  if (node.childNodes().size() == 0) {
   if (node.nodeName().equals("img")) { //Handles image path issues
    node.after("<p>${image_" + imgIndex + "}</p>"); //Add a P tag of the same level for img, the content is <P> The ${image_imgIndexNumber} </ P>
    String src = node.attr("src");
    node.remove(); //Remove the Img tag.
    StringBuffer imgUrl = new StringBuffer("D:TRSTRSWCMV65HBTCISWCMDatawebpic"); //Temporarily write the path directly to death, the formal application should rewrite this as the WebPic configuration item
    imgUrl.append(src.substring(0, 8)).append("").append(src.subSequence(0, 10)).append("").append(src);
    // node.attr("src", imgUrl.toString()); // This sentence is unnecessary because of this img The label has been removed 
    imgMap.put("${image_" + imgIndex++ + "}", imgUrl.toString());
   }
  } else {
   for (Node rNode : node.childNodes()) {
    sysElementText(rNode);
   }
  }
 }
}
 


Related articles: