Java实现PDF添加自定义水印

pom 依赖

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

yml 配置

默认模板【最好做成数据库动态配置】

#文件水印参数
oss:
  file:
    watermarkType: 1
    content: 仅供[[用户姓名]]-[[用户手机]]参考!
    fontTransparency: 0.3
    borderTransparency: 0.4
    fontSize: 30
    verticalInterval: 10.0
    horizontalInterval: 0.5
    rotationAngle: 30

参数实体类

import lombok.Data;

@Data
public class WatermarkParam {
    /**
     * 内容
     */
    private String content;
    /**
     * 字体透明度
     */
    private Float fontTransparency;
    /**
     * 边框透明度
     */
    private Float borderTransparency;
    /**
     * 字体字号
     */
    private Integer fontSize;
    /**
     * 纵间隔倍数
     */
    private Float verticalInterval;
    /**
     * 横间隔倍数
     */
    private Float horizontalInterval;
    /**
     * 旋转角度
     */
    private Long rotationAngle;
    /**
     * 1 中间一条  2 斜密条纹
     */
    private String watermarkType;
}

工具类

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.*;

import com.atguigu.springcloud.test.domain.bo.WatermarkParam;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;


public class PdfUtils {

    /**
     * 创建水印,返回文件字节数组
     *
     * @param file      文件
     * @param watermark 水印
     * @return
     */
    public static byte[] createConsumerWatermark(InputStream file, WatermarkParam watermark) {
        try {
            PdfReader reader = new PdfReader(file);
            PdfReader.unethicalreading = true;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(reader, out);
            stamper.setEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
            //字体编码
            BaseFont base = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            //水印透明度
            gs.setFillOpacity(watermark.getFontTransparency());
            //水印边框透明度
            gs.setStrokeOpacity(watermark.getBorderTransparency());
            int total = reader.getNumberOfPages() + 1;
            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 1;
            int textW = 2;
            label.setText(watermark.getContent());
            // 字体字号
            Font f = new Font("宋体", Font.BOLD, watermark.getFontSize());
            metrics = label.getFontMetrics(f);
            //角度
            if (watermark.getRotationAngle() >= 90) {
                textH = metrics.stringWidth(label.getText());
                textW = metrics.getHeight();
            } else {
                textH = metrics.getHeight();
                textW = metrics.stringWidth(label.getText());
            }
            PdfContentByte under;
            for (int i = 1; i < total; i++) {//遍历pdf每页
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, watermark.getFontSize());
                //under.setTextMatrix(0, 0);
                // 水印文字成30度角倾斜
                //你可以随心所欲的改你自己想要的角度
                //高度纵轴位置
                //如果是居中显示
                if (watermark.getWatermarkType().equals("1")) {
                    under.showTextAligned(Element.ALIGN_CENTER, watermark.getContent(), (pageRect.getWidth() / 2), (pageRect.getHeight() / 2), watermark.getRotationAngle());
                } else {
                    //密密麻麻
                    for (int height = textH; height < pageRect.getHeight(); height = height + (int) (textH * watermark.getVerticalInterval())) {
                        //长度横轴位置
                        for (int width = textW; width < pageRect.getWidth() + textW; width = width + (int) (textW * watermark.getHorizontalInterval())) {
                            under.showTextAligned(Element.ALIGN_LEFT, watermark.getContent(), width - textW, height - textH, watermark.getRotationAngle());
                        }
                    }
                }
                // 添加水印文字
                under.endText();
            }
            stamper.close();
            reader.close();
            return out.toByteArray();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
            throw new RuntimeException("文件加水印失败!");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌守

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值