java pdf 加水印

maven导入itextpdf依赖

	<!-- pdf添加水印 -->
		 <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.9</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
public class WaterPrintUtil {

	/**
	 * @param srcFile  pdf文件位置
	 * @param response 返回的响应流
	 * @param logoText 水印内容
	 * @param fileName 返回文件的名字
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static void addWaterMark(String srcFile, HttpServletResponse response, String logoText, String fileName)
			throws DocumentException, IOException {
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
		response.setContentType("application/pdf;charset=UTF-8");
		// 待加水印的文件
		PdfReader reader = new PdfReader(srcFile);
		// 加完水印的文件
		PdfStamper pdfStamper = new PdfStamper(reader, response.getOutputStream());
		int pageNumber = reader.getNumberOfPages() + 1;
		PdfContentByte content;
		// 检查字体文件存不存在
//		if (!new File(fontUrl).exists()) {
//			throw new RuntimeException(fontUrl + " 字体文件不存在");
//		}
		// 创建字体
//		BaseFont font = BaseFont.createFont(fontUrl, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		// 使用默认字体
		BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
		// 设置水印透明度
		PdfGState gs = new PdfGState();
		// 设置填充字体不透明度为0.3f
		gs.setFillOpacity(0.3f);
		// 循环对每页插入水印
		for (int i = 1; i < pageNumber; i++) {
			// 水印在之前文本下
			content = pdfStamper.getUnderContent(i);
			// 开始
			content.beginText();
			// 设置水印颜色(红色)
			content.setColorFill(BaseColor.RED);
			// 设置水印字体参数及大小 (字体参数,字体编码格式,是否将字体信息嵌入到pdf中(一般不需要嵌入),字体大小)
			content.setFontAndSize(font, 30);
			// 设置透明度
			content.setGState(gs);
			// 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
			content.showTextAligned(Element.ALIGN_RIGHT, logoText, 300, 0, 40);
			// 结束
			content.endText();
		}
		pdfStamper.close();
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值