给文件加水印(Word、PDF)并压缩
word分为doc文件和docx文件。HWPFDocument是用来操作doc文件的;XWPFDocument 是用来操作docx的。
由于当时无法创建HWPFDocument 对象,所以如果是doc文件的话会转换成docx然后再加水印。
@ApiOperation(value = "下载附件", notes = "下载附件")
@PostMapping("/download")
@ResponseBody
public ResponseEntity<FileSystemResource> download(@RequestBody NonLitigationVO nonLitigationVO, HttpServletResponse response) throws IOException, XmlException {
if (nonLitigationVO!=null&&nonLitigationVO.getAnnexId()!=null){
String annexId = nonLitigationVO.getAnnexId();
String[] split = annexId.split(",");
List<Attachment> attachments = attachmentMapper.selectByAttachmentIds(split);
if (attachments!=null&&attachments.size()>0){
//设置压缩路径f
String f =attachmentConfig.getPath()+"FS"+DateUtils.dateTimeNow("yyyyMMddHHmmss")+RandomUtil.randomNumbers(4)+"/";//DB adress
File file = new File(f);
//创建文件夹
boolean mkdirs = file.mkdirs();
for (Attachment attachment : attachments) {
// 给文件加水印
WatermarkUtil.addWatermark(new File(attachmentConfig.getPath() + attachment.getAttachmentAddress()),f); }
int length = file.listFiles().length;
//打包
File zip = ZipUtil.zip(f);
//导出
return export(zip);
}}
return null;
}
工具类
package com.boot.reservation.util;
import com.aspose.words.SaveFormat;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.ss.usermodel.*;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.springframework.util.FileCopyUtils;
import java.io.*;
import java.util.List;
import java.util.regex.Pattern;
import static com.boot.reservation.util.ExcelToPDFUtils.getLicense;
public class WatermarkUtil {
private static final String WATERMARK = "泰裤辣!!!!";
public static vo