JAVA给PDF添加水印

Java给PDF文件添加水印

因为在项目中需要用到这个功能所以自己写了一下,现在分享一下

加入maven依赖

代码片.

// An highlighted block
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.5.9</version>
</dependency>

代码实现

	/**
	 *
	 * @param InPdfFile 文件地址
	 * @param outPdfFile 输出文件地址
	 * @param textWatermark 水印文字
	 * @return
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static boolean addPngWatermark(String InPdfFile, String outPdfFile, String textWatermark)
			throws IOException, DocumentException {

		try {
			PdfReader reader = new PdfReader(InPdfFile);
			// reader.unethicalreading = true;
			PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outPdfFile));
			// 这里的字体设置比较关键,这个设置是支持中文的写法
			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);// 使用系统字体
			int total = reader.getNumberOfPages();
			// 文字的长度
			int l = textWatermark.length();
			int size = 0;
			if (l <= 6) {
				size = 22;
			}
			if (l > 6 && l <= 11) {
				size = 15;
			}
			if (l > 11) {
				size = 10;
			}
			if (l > 15) {
				size = 5;
			}
			Font f = new Font(base, size);
			Phrase p = new Phrase(textWatermark, f);
			// transparency
			PdfGState gs1 = new PdfGState();
			// 设置水印透明度
			gs1.setFillOpacity(0.4f);
			PdfContentByte over;
			com.itextpdf.text.Rectangle pagesize;
			for (int i = 1; i <= total; i++) {
				pagesize = reader.getPageSizeWithRotation(i);
				over = stamper.getOverContent(i);
				over.saveState();
				over.setGState(gs1);
				over.setTextMatrix(30, 30);
				over.setColorFill(BaseColor.GRAY);
				for (int y = 0; y < 10; y++) {
					for (int x = 0; x < 8; x++) {
						// 水印文字成45度角倾斜
						ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, 80 + 140 * x, 158 * y, -45);
					}
				}
				over.restoreState();
			}
			stamper.close();
			reader.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

测试效果

public static void main(String[] args) {
		try {
			PdfWatermark.addPngWatermark("D:\\home\\file\\vert-x-core-manual-for-java.pdf", "D:\\home\\file\\vert-x-core-manual-for-java_ceshi.pdf", "测试水印");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

在这里插入图片描述

结束语

这个就是Java给PDF添加水印的实现,期间也在网上找了些资料。有什么问题欢迎大家来交流

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值