itext5 PDF添加水印

本文介绍了如何使用Java编程语言中的iText库,通过PdfReader、PdfStamper和PdfContentByte等类实现PDF文件的水印添加功能,包括设置透明度、字体和加密选项。

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

/**
 * 添加文字水印
 * @param srcFile 待加水印文件
 * @param destFile 加水印后输出文件
 * @param text 文本内容
 * @throws Exception
 */
public static void addWaterMark(String srcFile, String destFile, String text) throws Exception {
    // 待加水印的文件
    PdfReader reader = new PdfReader(srcFile);
    // 加完水印的文件
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
    stamper.setEncryption(USER_PASS.getBytes(),OWNER_PASS.getBytes(),1,false);
    int total = reader.getNumberOfPages() + 1;
    PdfContentByte content;
    // 设置透明度
    PdfGState gs = new PdfGState();
    gs.setFillOpacity(0.05f);
    // 设置字体
    BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
    // 循环对每页插入水印
    for (int i = 1; i < total; i++)
    {
        // 水印的起始
        content = stamper.getOverContent(i);
        content.setGState(gs);
        content.setFontAndSize(base, 28);
        // 开始
        content.beginText();
        // 设置颜色 默认为黑色
        content.setColorFill(BaseColor.BLACK);
        // 开始写入水印
        content.showTextAligned(Element.ALIGN_MIDDLE, text, 100,
                50, 30);
        content.showTextAligned(Element.ALIGN_MIDDLE, text, 100,
                250, 30);
        content.showTextAligned(Element.ALIGN_MIDDLE, text, 100,
                450, 30);
        content.showTextAligned(Element.ALIGN_MIDDLE, text, 100,
                650, 30);

        content.showTextAligned(Element.ALIGN_MIDDLE, text, 300,
                50, 30);
        content.showTextAligned(Element.ALIGN_MIDDLE, text, 300,
                250, 30);
        content.showTextAligned(Element.ALIGN_MIDDLE, text, 300,
                450, 30);
        content.showTextAligned(Element.ALIGN_MIDDLE, text, 300,
                650, 30);
        content.endText();
    }
    stamper.close();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值