java为PDF添加水印,图片水印和文字水印

该博客介绍了如何使用Java的iText库为PDF文件添加水印,包括创建带有透明背景的文字水印图片以及将图片和文字作为水印添加到PDF中的方法。示例代码详细展示了如何生成水印图片、设置水印透明度和位置,并应用到PDF页面上。

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

java为PDF添加水印,文字水印和图片水印

一个需求,下载pdf、word、excel文件时要带有水印,要求铺满。先分开,先介绍为PDF文件添加文字水印和图片水印。
所需jar包:itext-2.0.1.jar。(itextpdf-5.5.8.jar,这个类似)
jar包可在这里下载:https://mvnrepository.com/

创建水印图片的类

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class ImageUtil {
	
	/**
	 * 生成背景透明的文字水印图片,文字位于中央,且倾斜
	 * @param content 水印文字
	 * @return
	 */
	public static BufferedImage createWaterMark(String content) {
		//生成图片宽度
		int width = 250;
		//生成图片高度
		int heigth = 160;
		//获取bufferedImage对象
		BufferedImage image = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);
		//得到画笔对象
		Graphics2D g2d = image.createGraphics();
		//使得背景透明
		image = g2d.getDeviceConfiguration().createCompatibleImage(width, heigth, Transparency.TRANSLUCENT);
		g2d.dispose();
		g2d = image.createGraphics();
		//设置对线段的锯齿状边缘处理
		g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		//设置水印旋转,倾斜度
		g2d.rotate(-0.5, (double) image.getWidth()/2, (double) image.getHeight()/2);
		//设置颜色,这是黑色,第4个参数是透明度
		g2d.setColor(new Color(0, 0, 0, 20));
		//设置字体
		Font font = new Font("宋体", Font.ROMAN_BASELINE, 22);
		g2d.setFont(font);
		float fontSize = font.getSize();
		//计算绘图偏移x、y,使得使得水印文字在图片中居中
		float x = 0.5f * fontSize;
		float y = 0.5f * heigth + x;
		//取绘制的字串宽度、高度中间点进行偏移,使得文字在图片坐标中居中
		g2d.drawString(content, x, y);
		//释放资源
		g2d.dispose();
		return image;
	}
	
	public static void main(String[] args) throws Exception {
		BufferedImage bi = createWaterMark("水印图片 2021-12-32");
		ImageIO.write(bi, "png", new File("E:\\waterMark.png")); //写入文件
	}
}

效果图

在这里插入图片描述

PDF添加图片水印的类

import java.io.FileOutputStream;

import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class PDFUtil {
	
	/**
	 * pdf文件添加图片水印
	 * itext-2.0.1.jar
	 * @param srcPath 输入的文件路径
	 * @param destPath 输出的文件路径
	 * @param imagePath 水印图片的路径
	 * @throws Exception
	 */
	public static void addPDFImageWaterMark(String srcPath, String destPath, String imagePath) 
			throws Exception {
		
		PdfReader reader = new PdfReader(srcPath);
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPath));
		
		//加载图片
		Image image = Image.getInstance(imagePath);
		
		PdfGState gs = new PdfGState();
		//gs.setFillOpacity(0.2f);//图片水印透明度
		//gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度
		PdfContentByte content = null;
		
		int total = reader.getNumberOfPages();//pdf文件页数
		for (int i=0; i<total; i++) {
			float x = reader.getPageSize(i+1).width();//页宽度
			float y = reader.getPageSize(i+1).height();//页高度
			content = stamper.getOverContent(i+1);
			content.setGState(gs);
			content.beginText();//开始写入
			
			//每页7行,一行3个
			for (int j=0; j<3; j++) {
				for (int k=0; k<7; k++) {
					//setAbsolutePosition 方法的参数(输出水印X轴位置,Y轴位置)
					image.setAbsolutePosition(x/3*j-30, y/7*k-20);
					content.addImage(image);
				}
			}
			content.endText();//结束写入
		}
		//关闭流
		stamper.close();
		reader.close();
	}
	
	public static void main(String[] args) throws Exception {
		addPDFImageWaterMark("E:\\测试.pdf", "E:\\测试水印img.pdf", "E:\\waterMark.png");
	}
}

效果图

在这里插入图片描述

PDF添加文字水印的类

与图片水印的类似,稍微改动

import java.io.FileOutputStream;

import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class PDFUtil {

	/**
	 * pdf文件添加文字水印
	 * @param srcPath 输入的文件路径
	 * @param destPath 输出的文件路径
	 * @param word 水印文字
	 * @throws Exception
	 */
	public static void addPDFWaterMark(String srcPath, String destPath, String word) 
			throws Exception {
		
		PdfReader reader = new PdfReader(srcPath);
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPath));
		
		//使用系统字体
		String prefixFont = null;
		String os = System.getProperties().getProperty("os.name");
		if (os.startsWith("win") || os.startsWith("Win")) {
			prefixFont = "C:\\Windows\\Fonts\\SIMSUN.TTC,1";
		} else {
			prefixFont = "/usr/share/fonts/chinese/TrueType/uming.ttf";
		}
		
		//创建字体,第一个参数是字体路径
		BaseFont base = BaseFont.createFont(prefixFont, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		//BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
		
		PdfGState gs = new PdfGState();
		gs.setFillOpacity(0.2f);//图片水印透明度
		//gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度
		PdfContentByte content = null;
		
		int total = reader.getNumberOfPages();//pdf文件页数
		for (int i=0; i<total; i++) {
			float x = reader.getPageSize(i+1).width();//页宽度
			float y = reader.getPageSize(i+1).height();//页高度
			content = stamper.getOverContent(i+1);
			content.setGState(gs);
			content.beginText();//开始写入
			content.setFontAndSize(base, 20);//字体大小
			//每页7行,一行3个
			for (int j=0; j<3; j++) {
				for (int k=0; k<7; k++) {
					//showTextAligned 方法的参数(文字对齐方式,位置内容,输出水印X轴位置,Y轴位置,旋转角度)
					content.showTextAligned(Element.ALIGN_CENTER, word, x/3*j+90, y/7*k, 25);
				}
			}
			content.endText();//结束写入
		}
		//关闭流
		stamper.close();
		reader.close();
	}
	
	public static void main(String[] args) throws Exception {
		addPDFWaterMark("E:\\测试.pdf", "E:\\测试水印.pdf", "水印测试 2021-12-32");
	}
}

效果图

在这里插入图片描述
若用的是itextpdf-5.5.8.jar,则需改动以下两处
float x = reader.getPageSize(i+1).getWidth(); //页宽度
float y = reader.getPageSize(i+1).getHeight(); //页高度

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值