给文件加水印(Word、PDF)并压缩

该文章介绍了如何使用Java处理Word和PDF文件,添加水印并进行压缩。通过ApachePOI库处理Word文档,Aspose库处理PDF,对文件加水印,并用ZipUtil进行打包压缩。代码示例展示了在API接口中实现这些功能的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给文件加水印(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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值