使用Aspose给PDF添加水印

Aspose相关使用参考这篇文章

封装工具类

java 复制代码
public class PdfOperationUtils {
    // 日志记录器,用于记录操作日志
    private static Logger logger = LogManager.getLogger(PdfOperationUtils.class);
    
    /**
     * pdf 加水印
     * @param pdfFile 原pdf文件
     * @param watermarkText 水印文字内容
     * @param tmpDir 临时文件目录(为空时使用系统默认临时目录)
     */
    public static void addWatermarkText(File pdfFile, String watermarkText, String tmpDir){
        // 如果临时目录为空,则使用系统默认的临时目录
        if(StringUtils.isBlank(tmpDir)) tmpDir=System.getProperty("java.io.tmpdir");
        // 在临时目录下创建一个以UUID命名的子目录,用于存放处理中的临时PDF文件
        File dir=new File(tmpDir, BaseUtils.getUUID(""));
        // 临时目录中与源文件同名的输出文件(加水印后的PDF先写入这里,最后覆盖源文件)
        File newPdfFile=new File(dir,pdfFile.getName());
        InputStream is = null;   // 源PDF输入流
        OutputStream os = null;  // 输出流
        com.aspose.pdf.Document pdfDocument = null; // Aspose PDF文档对象
        try {
            // 如果临时目录不存在,则创建(支持多级目录)
            if(!dir.exists()) {
                dir.mkdirs();
            }
            // 加载Aspose PDF许可证,去除水印/试用限制
            FileConvertUtils.loadAsposeLicense(FileConvertUtils.AsposeLicense_Type_Pdf);
            // 打开源PDF文件输入流
            is = new FileInputStream(pdfFile);
            // 创建临时输出文件流
            os = new FileOutputStream(newPdfFile);
            // 记录开始时间,用于统计耗时
            long old = System.currentTimeMillis();
            // 通过输入流加载PDF文档
            pdfDocument = new com.aspose.pdf.Document(is);
            
            // 遍历 PDF 的每一页,在每页上添加水印
            for (Page page : pdfDocument.getPages()) {
                // 创建水印工件(Artifact),比普通Stamp更适合做页面级水印
                WatermarkArtifact artifact = new WatermarkArtifact();
                // 设置水印文本:内容、颜色(灰色)、字体样式(Courier斜体)、编码、嵌入字体、字号72
                artifact.setText(new FormattedText(watermarkText,java.awt.Color.GRAY,FontStyle.CourierOblique,EncodingType.Identity_h,true,72.0F)); 
//                artifact.setImage(is); // 备用:如需图片水印可取消注释
                // 水平居中对齐
                artifact.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
                // 垂直居中对齐
                artifact.setArtifactVerticalAlignment(VerticalAlignment.Center);
                // 水印旋转角度45度
                artifact.setRotation(45);
                // 水印透明度0.3(半透明)
                artifact.setOpacity(0.3);
                // 不作为背景(即显示在内容之上)
                artifact.setBackground(false);
                // 将水印添加到当前页的工件集合中
                page.getArtifacts().add(artifact);
            }
            // 将添加水印后的PDF文档保存到临时输出流
            pdfDocument.save(os);
            
            // 关闭并释放输出流和输入流资源
            BaseUtils.clean(os,is);
            os=null;
            is=null;
            // 记录结束时间并输出耗时日志(单位:秒)
            long now = System.currentTimeMillis();
            logger.info("PdfOperationUtils.addWatermarkText 共耗时:" + ((now - old) / 1000.0) + "秒");
            // 用临时文件覆盖原PDF文件,完成加水印
            BaseUtils.copyFile(newPdfFile, pdfFile);
        } catch (Exception e) {
            // 捕获异常,记录错误日志并抛出运行时异常
            logger.error("pdf加水印失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            // 释放输出流、PDF文档对象、输入流等资源
            BaseUtils.clean(os,pdfDocument,is);
            // 删除临时PDF文件
            BaseUtils.deleteFile(newPdfFile);
            // 删除临时目录
            BaseUtils.deleteFile(dir);
        }
    }
}

测试

java 复制代码
    @Test
    public void pdfOperation() throws Exception {
        PdfOperationUtils.addWatermarkText(new File("F:/3.pdf"), "123", null);
    }

效果图

相关推荐
\光辉岁月/1 小时前
7.system类
java·system类
SL_staff1 小时前
BI落地失败的3个技术断点:从数据接入、自助分析到服务闭环的工程实践
java·数据分析·数据可视化
大风起兮云飞扬丶1 小时前
Java——线程池
java·开发语言
文丑颜不良啊2 小时前
LeetCode276~300题目解析
java·leetcode
Vegetable_xu2 小时前
Spring Bean 循环依赖:为什么有时能过、有时启动就挂
java·spring·mybatis
avi91113 小时前
【AI教人】在Inspector显示所有Delegate-Odin Inspector之三
java·前端·算法·delegate·inspector·editor扩展·unity editor
青春不朽5123 小时前
Python 的 list append 为什么是均摊 O(1)?拆开过度分配那张表,看容量翻倍背后的暗账
java·python·list
小羊没烦恼!4 小时前
.NET 11 Runtime Async 详解
java·运维·开发语言·javascript·python
哇嘎呀4 小时前
RHCSA题目
java·服务器·前端