一、工具类内容
* 替换文本 (每种字体有特定的字体字号)
* @param params key被替换字符,value content为替换内容 font为替换字体 fontSize为替换字号
* @param path 文件路径
* @param outPath 输出文件路径
*/
public static void replaceTextCustomization(Map<String, HashMap<String, Object>> params, String path, String outPath) throws FileNotFoundException {
XWPFDocument doc = openDocx(path);
for (XWPFParagraph paragraph : doc.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
for (Map.Entry<String, HashMap<String, Object>> entry : params.entrySet()) {
if (text != null && text.contains(entry.getKey())) {
text = text.replaceAll(entry.getKey(), entry.getValue().get("content").toString());
if (entry.getValue().get("font") != null) {
CTFonts font = run.getCTR().addNewRPr().addNewRFonts();
font.setEastAsia(entry.getValue().get("font").toString());
}
if (entry.getValue().get("fontSize") != null) {
run.setFontSize(Integer.parseInt(entry.getValue().get("fontSize").toString()));
}
run.setText(text, 0);
}
}
}
}
writeDocx(doc, new FileOutputStream(outPath));
}
/**
* 替换文本(统一设置字体字号)
* @param params 替换和被替换内容
* @param font 字体
* @param fontSize 字号
* @param path 文件路径
* @param outPath 输出文件路径
* @throws FileNotFoundException 错误
*/
public static void replaceText(Map<String, String> params, String font, int fontSize, String path, String outPath) throws FileNotFoundException {
XWPFDocument doc = openDocx(path);
for (XWPFParagraph paragraph : doc.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
for (Map.Entry<String, String> entry : params.entrySet()) {
if (text != null && text.contains(entry.getKey())) {
text = text.replaceAll(entry.getKey(), entry.getValue());
if (font != null && !"".equals(font)) {
CTFonts fontSet = run.getCTR().addNewRPr().addNewRFonts();
fontSet.setEastAsia(font);
}
if (fontSize != 0) {
run.setFontSize(fontSize);
}
run.setText(text, 0);
}
}
}
}
writeDocx(doc, new FileOutputStream(outPath));
}
/**
* @param url 获取文档对象的路径
* @return XWPFDocument 返回文档对象
* */
public static XWPFDocument openDocx(String url) {
XWPFDocument doc = null;
try (InputStream input = new FileInputStream(url)) {
doc = new XWPFDocument(input);
return doc;
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
/**
* @param outDoc 输出的文档对象
* @param out 输出内容
* @return void
* */
public static void writeDocx(XWPFDocument outDoc, OutputStream out) {
try {
outDoc.write(out);
out.flush();
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}