使用开源的itext对pdf格式的文件添加文字水印

该博客介绍了一种使用开源库iText在Java中为PDF文件添加文字水印的方法。通过创建一个工具类`PdfAddWaterUtil`,实现了读取PDF,设置水印内容、透明度、字体大小等参数,并将水印添加到每一页的指定位置。最终,加了水印的PDF文件被保存到目标路径,并且可以设置编辑密码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用开源的itext对pdf格式的文件添加文字水印

一、工具类

package test;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
* @Description //使用开源的 itext 为pdf格式的文件加水印
* @Date
* @Param
* @return
*/
public class PdfAddWaterUtil {
    public static void main(String[] args) throws DocumentException,IOException {
    	String pdfsourcepath="C:/Users/Administrator/Desktop/1.pdf";
        String pdftargetpath="C:/Users/Administrator/Desktop/111.pdf";
        Calendar cal = Calendar.getInstance();  
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
        String waterMarkName="521:"+"br~"+format.format(cal.getTime());
        addWatermark(pdfsourcepath, pdftargetpath,waterMarkName);
    }

        public static  void addWatermark(String pdfsourcepath, String pdftargetpath,String waterMarkName) throws DocumentException,IOException {
    	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(pdftargetpath)));
        String pdfpassword = "test";

        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(pdfsourcepath, pdfpassword.getBytes());  //如果pdf受密码保护时,应先根据密码解决,否则读取pdf失败
            stamper = new PdfStamper(reader, bos);
            stamper.setEncryption(null, pdfpassword.getBytes(), 4, false);   //设置编辑受限的密码保护

            int total = reader.getNumberOfPages() + 1;
            PdfContentByte content;
            //BaseFont base = BaseFont.createFont(BaseFont.COURIER, "UTF-8",BaseFont.EMBEDDED);
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            float opacity = Float.parseFloat("0.5");   //水印透明度,值从0.0到1.0,1代表不透明,0代表透明
            String waterShowLevel = "1";   //水印内容显示在文字上面还是下面,0代表下面,1代表上面

            int r = 128;
            int g = 128;
            int b = 128;

            float waterFontSize = Float.parseFloat("16");  //水印字体大小
            float waterGradient = Float.parseFloat("30");  //水印内容倾斜度
            int lineCount = 7;   //水印内容行数
            int xwaterSpace = 60;   //水印内容水平间距
            int ywaterSpace = 90;  //水印内容行间距
            int waterLoopCount = 3;  //水印内容循环次数
            String newwaterMarkName = waterMarkName;
            if (waterLoopCount > 1) {
                for (int loopcount = 0; loopcount < waterLoopCount; loopcount++) {
                    newwaterMarkName += "                " + waterMarkName;
                }
            }
            int xstart = xwaterSpace * (lineCount - 1) / 2;
            int ystart = ywaterSpace * (lineCount - 1) / 2;
            gs.setFillOpacity(opacity);
            gs.setStrokeOpacity(opacity);
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().getPageSizeWithRotation(i);
                float x = pageRect.getWidth() / 2;
                float y = pageRect.getHeight() / 2;
                if ("1".equals(waterShowLevel)) {
                    content = stamper.getOverContent(i);// 在内容上方加水印
                } else {
                    content = stamper.getUnderContent(i);// 在内容下方加水印
                }
                content.setGState(gs);
                content.beginText();
                content.setColorFill(new BaseColor(r, g, b));
                content.setFontAndSize(base, waterFontSize);
                content.setTextMatrix(0, 0);
                for (int num = 0; num < lineCount; num++) {
                    content.showTextAligned(Element.ALIGN_CENTER, newwaterMarkName, x - xstart + (num * xwaterSpace), y + ystart - (num * ywaterSpace), waterGradient);
                }
                content.endText();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(stamper != null){
                stamper.close();
            }
            if(reader != null){
                reader.close();
            }
        }
    }
}  

二、使用到的jar包:
在这里插入图片描述

三、效果
(1)加水印前:
在这里插入图片描述
(2)加水印后:并带有编辑密码。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值