Doc2Docx 主函数
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.aspose.words.Document;
public class Doc2Docx {
public static void main(String[] args) {
String docFile = "E:\\poi\\2.doc";
String docxFile = "E:\\poi\\x2.docx";
doc2docx(docFile, docxFile);
}
public static void doc2docx(String docFile, String docxFile) {
Document doc;
try {
String tempFile = docxFile.substring(0, docxFile.lastIndexOf(".")) + "_temp"
+ docxFile.substring(docxFile.lastIndexOf("."), docxFile.length());
doc = new Document(docFile);
doc.save(tempFile);
Map<String, String> map = new HashMap<String, String>();
map.put("Evaluation Only. Created with Aspose.Words. Copyright 2003-2018 Aspose Pty Ltd.", "");
// 使用 aspose不使用license.xml会产生,替换水印的文字
DocxReplace.replaceAndGenerateWord(tempFile, docxFile, map);
// 删除临时文件
forceDelete(new File(tempFile));
} catch (Exception e1) {
e1.printStackTrace();
}
}
public static boolean forceDelete(File file) {
boolean result = file.delete();
int tryCount = 0;
while (!result && tryCount++ < 10) {
System.gc();
result = file.delete();
}
return result;
}
}
DocxReplace 替换水印
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class DocxReplace {
// 返回Docx中需要替换的特殊字符,没有重复项
// 推荐传入正则表达式参数"\\$\\{[^{}]+\\}"
public Ar