先通过freemaker模板得到word文档通过aspose.words 中的Document读取文档,使用aspose.words Shape添加水印
public static void exportWordWaterMark(String templateName, Map<String, Object> data, String docName, HttpServletResponse response,String watermarkText,String format) {
// 初始化配置文件
Configuration configuration = new Configuration();
// 设置编码
configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
// 获取文件所在文件夹
configuration.setClassForTemplateLoading(WordUtil.class, "/template");
// fileDirectory目录下的模板文件名
Template template = null;
try {
template = configuration.getTemplate(templateName);
} catch (IOException e) {
throw new BusinessException("doc模板文件未找到");
}
Writer out = null;
try {
// 使用FreeMarker填充数据
StringWriter stringWriter = new StringWriter();
template.process(data, stringWriter);
String generatedContent = stringWriter.toString();
// 将FreeMarker生成的Word文档保存为临时文件
OutputStream outputStream = new FileOutputStream("temp.docx");
outputStream.write(generatedContent.getBytes());
outputStream.close();
// 使用Aspose.Words读取保存的Word文档
AsposeUtil.getLicense();
Document doc = new Document("temp.docx");
Paragraph watermarkPara = new Paragraph(doc);
//循环添加水印,这里横纵都在一条水平线,不太好看,可以对i和j控制使之有适当位移
for (int j = -50; j < 700; j = j + 200) {
for (int i = 50; i < 700; i = i + 100) {
Shape waterShape = ShapeMore(doc, watermarkText, j, i);
watermarkPara.appendChild(waterShape);
}
}
for (Section sect : doc.getSections())
{
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);
insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
}
// 设置HTTP响应头,将生成的Word文档作为附件下载
docName = URLEncoder.encode(docName, Charsets.UTF_8.name());
response.setHeader("Content-disposition", "attachment;filename=" + docName + "." + format);
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
// 将带水印的Word文档写入响应输出流
OutputStream servletOutputStream = response.getOutputStream();
if (Func.equals("pdf",format)) {
doc.save(servletOutputStream, SaveFormat.PDF);
} else if (Func.equals("doc",format)) {
doc.save(servletOutputStream, SaveFormat.DOC);
} else if (Func.equals("docx",format)) {
doc.save(servletOutputStream, SaveFormat.DOCX);
} else {
throw new BusinessException("文件格式未找到!");
}
// 删除临时文件
File tempFile = new File("temp.docx");
tempFile.delete();
} catch (IOException e) {
throw new BusinessException("doc模板文件未找到!");
} catch (TemplateException e) {
throw new BusinessException("解析模板生成word失败!");
} finally {
if (out != null) {
out.close();
}
}
}
处理页眉
如果文档有页眉页眉会无水印,以下代码处理页眉,添加水印
private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception{
HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
if (header == null)
{
header = new HeaderFooter(sect.getDocument(), headerType);
sect.getHeadersFooters().add(header);
}
header.appendChild(watermarkPara.deepClone(true));
}
获取字体
操作文档,添加水印,两种办法获取字体,setFontFamily获取系统字体,如果Linux中不存在该字体会报错,需要Linux下载该字体
例如:微软雅黑,在Windows操作系统中,常见的系统字体文件通常存储在以下路径下:
C:\Windows\Fonts
在这个路径下获取字体放到Linux /usr/share/fonts路径中,通过下面代码更新字体缓存
sudo fc-cache -f -v
查看是否安装成功
fc-list | grep "Microsoft YaHei"
第二种自定义字体
ClassPathResource("font/simsun.ttf")读取字体文件,ClassPathResource读取路径在resources静态文件夹下
InputStream inputStream = null;
try {
ClassPathResource classPathResource = new ClassPathResource("font/simsun.ttf");
inputStream = classPathResource.getInputStream();
// String fontPath = "font/simsun.TTF";
Font customFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
waterShape.getTextPath().setFontFamily(customFont.getFontName());
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
添加水印
public static Shape ShapeMore(Document doc, String watermarkText, double left, double top){
Shape waterShape = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
//水印内容
waterShape.getTextPath().setText(watermarkText);
//水印字体
waterShape.getTextPath().setFontFamily("Microsoft YaHei");
// // 水印字体
// InputStream inputStream = null;
// try {
// ClassPathResource classPathResource = new ClassPathResource("font/simsun.ttf");
// inputStream = classPathResource.getInputStream();
//// String fontPath = "font/simsun.TTF";
// Font customFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
// waterShape.getTextPath().setFontFamily(customFont.getFontName());
// } catch (FontFormatException | IOException e) {
// e.printStackTrace();
// }
try {
//具体字体内容大小进行自定义设置
waterShape.setWidth(72);//水印宽度
waterShape.setHeight(18);//水印高度
} catch (Exception e) {
e.printStackTrace();
}
//旋转水印
waterShape.setRotation(-40);
//填充颜色(没有填充颜色字会变成空心的)
waterShape.getFill().setColor(new Color(217,217,217));
//水印颜色 浅灰色
waterShape.setStrokeColor(new Color(217,217,217));
//将水印放置在页面中心
waterShape.setLeft(left);
waterShape.setTop(top);
//设置包装类型
waterShape.setWrapType(WrapType.NONE);
return waterShape;
}