PDF文件增加图片水印(盖章)

1.增加pom依赖

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

 2.java工具方法

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfStamper stamp = null;
        PdfReader reader = null;

        try {
            //获取创建读取Pdf文件流对象
            reader = new PdfReader("pdf文件路径");
            stamp = new PdfStamper(reader, outputStream);

            //pdf文件页数
            int keywords = reader.getNumberOfPages();
            // 插入水印
            Image img = Image.getInstance("印章文件路径");
            // 水印透明度设置
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(0.8f);

            //遍历文件页数,可用于多页签字
            for (int i = 1; i <= keywords; i++) {
                //签字第几页 getUnderContent:在内容下方,getOverContent:在内容上方
                PdfContentByte pdfContentByte = stamp.getOverContent(keywords);
                //设置图片长和宽
                img.scaleAbsolute(200, 100);
                //插入水印位置坐标
                img.setAbsolutePosition(300, 100);
                //img.setRotation(-20);// 旋转 弧度
                //img.setRotationDegrees(45);// 旋转 角度
                // img.scalePercent(50);//依照比例缩放

                // 图片水印 透明度
                pdfContentByte.setGState(gs1);
                //插入图片水印
                pdfContentByte.addImage(img);
            }

            //关闭流
            stamp.close();
            //生成新文件
            File tempFile = new File("合成新文件路径");
            if (!tempFile.exists()) {
                tempFile.createNewFile();
            }
            //写入新文件内容
            FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
            fileOutputStream.write(outputStream.toByteArray());
            fileOutputStream.close();
            //base64字节流数据
            //String output = Base64.encodeBase64String(outputStream.toByteArray());
            System.out.println("签字盖章成功");

        }catch (Exception e){
            System.out.println("签字盖章异常:"+e);
        } finally {
            if (null != reader) {
                reader.close();
            }
        }

3.项目运行,OK

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值