@struts文件上传doc或者docx文档(文档中本身有页眉),最终是将文档转换成图片
将上传的文件中的页眉替换为新的页眉内容,例如本身上传的文档中的页眉是:测试页眉,而项目中需要修改为“20190524001”,那么就需要在上传的时候,将文件上传到项目中的webapp中的某个目录下,然后将这个文件的页眉替换掉,然后在转换为图片上传保存,具体代码
在上传的时候,判断文档是doc或者docx以后
//临时保存上传的文件destFile
final String destPath = ServletActionContext.getServletContext().getRealPath("doc/");
File destFile = new File(destPath, fileName);
FileUtils.copyFile(file, destFile);
// 添加页眉
WordReplaceText.wordReplaceText(destPath+fileName,"内部资料 请勿外传",fileinfoFormVo.getCode(),destPath+fileName.substring(0,fileName.lastIndexOf("."))+"1."+suffix);
this.file=new File(destPath+fileName.substring(0,fileName.lastIndexOf("."))+"1."+suffix);
//删除原文件
destFile.delete();
//word文档转换为图片
saveImgData(realPath, fileId, GlobalVariable.WORD);
//删除临时文件
this.file.delete();
//替换页眉:参数说明;第一个:源文件,原页眉,目标页眉,修改后新的文件
public static void wordReplaceText(String sourceWord, String oldChar, String newChar, String newWord) {
//加载Word文档
Document document = new Document(sourceWord);
//使用新文本替换文档中的指定文本
document.replace(oldChar, newChar, false, true);
//保存文档
document.saveToFile(newWord, FileFormat.Docx_2013);
}