pdf添加水印

该文章提供了一个Java代码示例,展示了如何为PDF文件添加水印,包括调整水印的位置、倾斜度、透明度、字体大小、颜色以及数量。使用了PDDocument和PDPageContentStream等PDF处理库,强调了需引入特定字体以使水印生效。
摘要由CSDN通过智能技术生成

水印位置、倾斜度、透明度、字体大小、颜色、条数可自行调整;

话不多说直接上代码!!!

    File tempFile = new File("F:\\6665.pdf");
        String waterMark = "测试水印";
        float fontSize = 20;
        int[] color = {200, 0, 0};
        int rowSpace = 200;
        int colSpace = 200;
        try {
            waterMarkUtil(tempFile, waterMark, fontSize, color, rowSpace, colSpace);
        } catch (IOException e) {
            System.out.println("水印渲染异常:" + e);
        }

 

具体实现如下:

tempFile: 需要添加水印的文件

waterMark: 需要添加的水印文字

rowSpace、colSpace:倾斜度

color: 颜色,我这里使用的红色

fontSize: 文字大小

需要用到字体:使用默认字体不生效,最好是引入字体

​
 private static void waterMarkUtil(File tempFile, String waterMark, float fontSize, int[] color, int rowSpace, int colSpace) throws IOException {
        // 加载PDF文件
        PDDocument document = PDDocument.load(tempFile);
        document.setAllSecurityToBeRemoved(true);

        // 遍历PDF文件,在每一页加上水印
        for (PDPage page : document.getPages()) {
            PDPageContentStream stream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);

            // 加载水印字体
            PDFont font = PDType0Font.load(document, Files.newInputStream(Paths.get("C:\\Users\\Desktop\\仿宋_GB2312.ttf")), true);

            PDExtendedGraphicsState r = new PDExtendedGraphicsState();

            // 设置透明度
            r.setNonStrokingAlphaConstant(0.1f);
            r.setAlphaSourceFlag(true);
            stream.setGraphicsStateParameters(r);

            // 设置水印字体颜色
            if (color.length == 3) {
                stream.setNonStrokingColor(color[0], color[1], color[2]);
            }
            stream.beginText();
            stream.setFont(font, fontSize);
            stream.newLineAtOffset(0, -15);

            // 获取PDF页面大小
            float pageHeight = page.getMediaBox().getHeight();
            float pageWidth = page.getMediaBox().getWidth();

            // 根据纸张大小添加水印,30度倾斜
            for (int h = 10; h < pageHeight; h = h + rowSpace) {
                for (int w = -10; w < pageWidth; w = w + colSpace) {
                    stream.setTextMatrix(Matrix.getRotateInstance(0.3, w, h));
                    stream.showText(waterMark);
                }
            }

            // 结束渲染,关闭流
            stream.endText();
            stream.restoreGraphicsState();
            stream.close();
        }
        document.save(tempFile);
    }

​

结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值