iText实现pdf添加文字水印

iText实现pdf添加文字水印
1.添加maven依赖
 		<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
2.代码实现
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @description: pdf文档操作utils
 * @author: wzg
 * @create: 2021-12-16
 **/
public class PdfUtils {


    public static void main(String[] args) throws Exception {

        //需要添加水印的文件
        String inputFile = "D:\\data\\doc\\2021-12-15\\百强县分析报告1639532278835.pdf";
        //添加完水印的文件存放路径
        String outputFile = "D:\\data\\doc\\2021-12-15\\百强县分析报告1639532278835(水印).pdf";
        //需要添加的水印文字
        String waterMarkName = "添加水印";
        //水印字体透明度
        float opacity = 0.3f;
        //水印字体大小
        int fontsize = 40;
        //水印倾斜角度(0-360)
        int angle = 30;
        //数值越大每页竖向水印越少
        int heightDensity = 50;
        //数值越大每页横向水印越少
        int widthDensity = 10;

        PdfUtils.addWaterMark(inputFile, outputFile, waterMarkName, opacity, fontsize, angle, heightDensity, widthDensity,false);
    }


    /**
     * pdf添加水印
     * @param inputFile 需要添加水印的文件
     * @param outputFile 添加完水印的文件存放路径
     * @param waterMarkName 需要添加的水印文字
     * @param opacity 水印字体透明度
     * @param fontsize 水印字体大小
     * @param angle 水印倾斜角度(0-360)
     * @param heightDensity 数值越大每页竖向水印越少
     * @param widthDensity 数值越大每页横向水印越少
     * @param cover 是否覆盖
     * @return
     */
    public static boolean addWaterMark(String inputFile, String outputFile, String waterMarkName,
                                       float opacity, int fontsize, int angle, int heightDensity, int widthDensity,boolean cover) {
        if (!cover){
            File file=new File(outputFile);
            if (file.exists()){
                return true;
            }
        }
        File file=new File(inputFile);
        if (!file.exists()){
            return false;
        }

        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            int interval = -5;
            reader = new PdfReader(inputFile);
            stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            //这里是透明度设置
            gs.setFillOpacity(opacity);
            //这里是条纹不透明度
            gs.setStrokeOpacity(0.2f);
            int total = reader.getNumberOfPages() + 1;
            System.out.println("Pdf页数:" + reader.getNumberOfPages());
            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            //字符串的高,   只和字体有关
            textH = metrics.getHeight();
            //字符串的宽
            textW = metrics.stringWidth(label.getText());
            PdfContentByte under;
            //循环PDF,每页添加水印
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);  //在内容上方添加水印
                //under = stamper.getUnderContent(i);  //在内容下方添加水印
                under.saveState();
                under.setGState(gs);
                under.beginText();
                //under.setColorFill(BaseColor.PINK);  //添加文字颜色  不能动态改变 放弃使用
                under.setFontAndSize(base, fontsize); //这里是水印字体大小
                for (int height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) {
                    for (int width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) {
                        // rotation:倾斜角度
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, angle);
                    }
                }
                //添加水印文字
                under.endText();
            }
            System.out.println("添加水印成功!");
            return true;
        } catch (IOException e) {
            System.out.println("添加水印失败!错误信息为: " + e);
            e.printStackTrace();
            return false;
        } catch (DocumentException e) {
            System.out.println("添加水印失败!错误信息为: " + e);
            e.printStackTrace();
            return false;
        } finally {
            //关闭流
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                reader.close();
            }
        }
    }
}
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值