java对pdf文件添加水印

java对pdf文件添加水印

添加依赖

xml 复制代码
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

参考代码

java 复制代码
private final static Map<String,Object> pdfConfig = getPdfDefaultConfig();



    public static Map<String,Object> getPdfDefaultConfig(){
        Map<String, Object> config = new HashMap<>();
        try {
            config.put("baseFont", BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",   BaseFont.EMBEDDED));
        } catch (IOException | DocumentException e) {
            throw new RuntimeException(e);
        }
        config.put("fillOpacity",0.3f);// 填充透明度
        config.put("strokeOpacity",0.4f);// 笔划不透明度
        config.put("fontSize",16);//字体大小
        config.put("interval",-15);// 水印间隔
        config.put("rotation",30);// 旋转角度
        return config;
    }

    public static void pdfByText(InputStream inputStream, OutputStream outputStream, String waterMarkName, Map<String,Object> config) throws DocumentException, IOException {
        PdfReader reader = new PdfReader(inputStream);
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        try {

            BaseFont base = (BaseFont) config.getOrDefault("baseFont",pdfConfig.get("baseFont"));

            com.itextpdf.text.Rectangle pageRect;
            PdfGState gs = new PdfGState();
            gs.setFillOpacity((Float) config.getOrDefault("fillOpacity",pdfConfig.get("fillOpacity")));
            gs.setStrokeOpacity((Float) config.getOrDefault("strokeOpacity",pdfConfig.get("strokeOpacity")));
            int total = reader.getNumberOfPages() + 1;

            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH;
            int textW;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());

            PdfContentByte under;
            int interval = (int) config.getOrDefault("interval", pdfConfig.get("interval"));
            int rotation = (int) config.getOrDefault("rotation", pdfConfig.get("rotation"));
            int fontSize = (int) config.getOrDefault("fontSize", pdfConfig.get("fontSize"));
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, fontSize);


                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 3) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 2) {
                        under.showTextAligned(Element.ALIGN_LEFT
                                , waterMarkName, width - textW, height - textH, rotation);
                    }
                }
                // 添加水印文字
                under.endText();
            }

        } finally {
            stamper.close();
            reader.close();
        }
    }

测试

java 复制代码
public static void main(String[] args) throws IOException, DocumentException {
        pdfByText( new FileInputStream("F:\\tmp\\1\\python基于深度学习的音乐推荐方法研究系统.pdf"), new FileOutputStream("F:\\tmp\\1\\python基于深度学习的音乐推荐方法研究系统-pdf.pdf"),"测试水印-abments", new HashMap<>());
    }

效果展示

说明

方法pdfByText的参数设置为InputStream inputStream, OutputStream outputStream,是为了方便java中直接输出给响应体对象。

在使用过程如果遇到问题欢迎留言讨论。

相关推荐
pengyu1 分钟前
【Java设计原则与模式之系统化精讲:壹】 | 编程世界的道与术(实战指导篇)
java·后端·设计模式
砖厂小工2 分钟前
Now In Android 精讲 8 - Gradle build-logic 现代构建逻辑组织方式
android
日月星辰Ace4 分钟前
JVM 垃圾回收简介
java
掉头发的王富贵7 分钟前
Arthas神器入门:动态调试Java应用,轻松搞定生产环境Bug!
java·后端·debug
玲小珑11 分钟前
Auto.js 入门指南(八)高级控件与 UI 自动化
android·前端
Java陈序员12 分钟前
再见 Navicat!一款开源的 Web 数据库管理工具!
java·react.js·docker
harry235day24 分钟前
Compose 带动画的待办清单列表页
android·android jetpack
vocal24 分钟前
我的安卓第一课:四大组件之一Activity及其组件RecyclerView
android
知其然亦知其所以然28 分钟前
RAG 结果太水?用 RRF + Reranker 重排,效果翻倍提升!
java·后端·llm
SimonKing30 分钟前
吊打面试官系列:Spring为什么不推荐使用字段依赖注入?
java·后端·架构