前言
最近需要将word文档输出为pdf,然后觉得全是文字的pdf看着太单调了,想给它加点好看的图片水印。刚好以前有写过给PDF加图片水印的方法,所以就直接拿过来用了,经过多次调试和修改,就实现了以下效果。
效果
这是原页面
左上角
左下角
右上角
右下角
居中
不管有多少页,每一页的水印都是生效的。同时它也是可以设置多个水印的,比如在右上角和中间设置不同的图片水印,这也是可以的。
居中和右上角
实现
接下来我们来看看具体的实现代码。
给PDF生成水印,我们需要用到生成PDF的依赖,这里我用的是xhtmlrenderer的core-renderer:
<!--pdf生成工具类-->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>core-renderer</artifactId>
<version>R8</version>
</dependency>
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws Exception {
String inputFile = "C:\\Users\\Administrator\\Desktop\\测试.pdf";
String outputFile = "C:\\Users\\Administrator\\Desktop\\居中和右上角.pdf";
String [] images = {
"D:\\Program Files\\鼠标指针\\自定义文件夹背景\\Image\\戍边中.jpg","E:\\document\\图片\\米游社表情包\\图片\\逢考必过.png"};
String [] positions = {
"居中","右上角"};
addPDFLogo(inputFile,outputFile,images,positions);
}
/**
* pdf文件添加图片水印
* @param InPdfFile 要添加水印的pdf路径
* @param outPdfFile 添加水印完成的pdf输入路径
* @param images 添加图片水印的路径,可以设置多个
* @param positions 与图片水印对应的位置
*/
public static void addPDFLogo(String InPdfFile, String outPdfFile, String [] images,String [] positions) throws IOException, DocumentException {
System.out.println("========开始生成水印========>>>>>>" + InPdfFile);
PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));
Rectangle cropBox = reader.getPageSize(1);// 获取pdf页面区域
PdfContentByte under;
PdfGState gs1 = new PdfGState();
gs1.setFillOpacity(0.3f); // 透明度设置
Image img = null;
for (int i = 0; i < images.length; i++) {
img = Image.getInstance(images[i]);// 插入图片水印
String position = positions[i];
switch (position){
case "居中":
img.setAbsolutePosition((cropBox.getWidth() - img.getWidth()) / 2,(cropBox.getHeight() -img.getHeight()) / 2); // 居中
break;
case "左上角":
img.setAbsolutePosition(0, cropBox.getHeight() - img.getHeight()); // 左上角
break;
case "左下角":
img.setAbsolutePosition(0, 0); // 左下角
break;
case "右上角":
img.setAbsolutePosition(cropBox.getWidth() - img.getWidth(),cropBox.getHeight() - img.getHeight()); // 右上角
break;
case "右下角":
img.setAbsolutePosition(cropBox.getWidth() - img.getWidth(),0); // 右下角
break;
}
img.setRotation(0);// 旋转 弧度
img.setRotationDegrees(0);// 旋转 角度
int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
for (int j = 1; j <= pageSize; j++) {
under = stamp.getUnderContent(j); // 水印在之前文本下
// under = stamp.getOverContent(i); //水印在之前文本上
under.setGState(gs1); // 图片水印 透明度
under.addImage(img); // 图片水印
}
}
System.out.println("========完成水印生成========>>>>>>" + outPdfFile);
stamp.close();// 关闭
reader.close();
}
}
以上就是全部代码了。