前段时间接到一个需求,要把一个java生成的word文档转换成PDF。本来挺简单的事儿,结果发现转换之后的文档中不展示生僻字,检查了半天才发现是因为word文档的字体不包含生僻字,而我们还不能换成别的字体,经过与客户商议,决定word文档的整体的字体不能改变,但是生僻字的字体是可以改为宋体的。但是这就带来一个问题——如何替换word文档中随机出现的生僻字的字体呢?联想到之前做过的一个解析word文档的功能,我想到了一个办法——把识别到的生僻字用宋体的字体标签围住,然后重新组合成word文档。想到就做,以下是关键代码:
package com.example.sb_1;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
@Slf4j
public class XmlUtil {
public static String dealRareWords(String wordUrl, String targetUrl, String busId, Map<String, Object> dataMap) {
StringBuilder lessWords = new StringBuilder();
String[] strs;
File file;
ZipFile docxFile;
ZipEntry documentXML;
InputStream documentXMLIS;
InputStreamReader isr = null;
FileOutputStream fos = null;
PrintWriter pw = null;
BufferedReader br = null;
String newDocx = "";
DocumentBuilderFactory dbf;
Document doc;
DocumentBuilderFactory dbfCopy;
Document docCopy;
try {
//扫描数据中的生僻字,dataMap里面是word文档里面已经识别到的所有文字
for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
strs = JSONObject.toJSONString(entry.getValue()).split("");
//遍历识别所有的生僻字,放入lessWords
for (String str : strs) {
if (str.equals(new String(str.getBytes("gb18030"), "gb2312"))) {
lessWords.append(str).append(",");
}
}
}
String words = lessWords.length() == 0 ? "" : lessWords.substring(0, lessWords.length() - 1);
if (!words.isEmpty()) {
//获取已生成的word文档
file = new File(wordUrl);
docxFile = new ZipFile(file);
documentXML = docxFile.getEntry("word/document.xml");
documentXMLIS = docxFile.getInputStream(documentXML);
isr = new InputStreamReader(documentXMLIS);
br = new BufferedReader(isr);
String row;
StringBuilder buf = new StringBuilder();
String[] lesses = words.split(",");
//新xml文件目录
String xmlFilePath = targetUrl + File.separator + busId + "document.xml";
while ((row = br.readLine()) != null) {
for (String less : lesses) {
if (row.contains(less)) {
row = row.replace(less, "</w:t></w:r><w:r><w:rPr><w:rFonts w:eastAsia=\"宋体\"" +
" w:hint=\"eastAsia\"/></w:rPr><w:t>" + less + "</w:t></w:r>");
}
}
buf.append(row);
}
File xmlFile = new File(xmlFilePath);
if (!xmlFile.exists()) {
xmlFile.createNewFile();
}
fos = new FileOutputStream(xmlFile);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
//替换原有的document.xml
newDocx = targetUrl + File.separator + busId + "document.xml";
dbf = DocumentBuilderFactory.newInstance();
doc = dbf.newDocumentBuilder().parse(xmlFile);
Transformer t = TransformerFactory.newInstance().newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.transform(new DOMSource(doc), new StreamResult(baos));
ZipOutputStream docxOutFile = new ZipOutputStream(Files.newOutputStream(Paths.get(newDocx)));
Enumeration<? extends ZipEntry> entriesIter = docxFile.entries();
while (entriesIter.hasMoreElements()) {
ZipEntry entry = entriesIter.nextElement();
//如果是document则修改,别的文件直接拷贝,不改变word样式
if (entry.getName().equals("word/document.xml")) {
byte[] data = baos.toByteArray();
docxOutFile.putNextEntry(new ZipEntry(entry.getName()));
docxOutFile.write(data, 0, data.length);
docxOutFile.closeEntry();
} else {
InputStream incoming = docxFile.getInputStream(entry);
dbfCopy = DocumentBuilderFactory.newInstance();
docCopy = dbfCopy.newDocumentBuilder().parse(incoming);
Transformer tCopy = TransformerFactory.newInstance().newTransformer();
ByteArrayOutputStream baosCopy = new ByteArrayOutputStream();
tCopy.transform(new DOMSource(docCopy), new StreamResult(baosCopy));
byte[] b = baosCopy.toByteArray();
docxOutFile.putNextEntry(new ZipEntry(entry.getName()));
docxOutFile.write(b, 0, b.length);
docxOutFile.closeEntry();
if (incoming != null) {
incoming.close();
}
baosCopy.close();
}
}
}
} catch (Exception e) {
log.error("", e);
} finally {
try {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
} catch (Exception e) {
log.error("", e);
}
}
return newDocx;
}
}
上述方法仅支持docx格式的word文档,如果文档中不存在生僻字,则会返回一个空字符串,如果存在生僻字,则会返回新文档的路径。过程有点儿复杂,应该还有优化空间,不过鉴于使用的场景比较特殊,用的比较少,也就没有细究了。如果各位有更简单的方式,欢迎交流!