可直接复制粘贴到测试类中,进行测试,当做随手笔记了,用的时候方便
jar:
iText-2.0.8.jar
iTextAsian.jar
import java.awt.Color;
import java.awt.FontMetrics;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JLabel;
import com.lnlic.credit.common.core.util.ItextUtil;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
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;
/**
* 测试PDF添加水印
*
* @Description:
* @ClassName: TestPDF
* @Author 我的花儿
* @DateTime 2019年12月3日 下午1:41:03
*/
public class TestPDF {
private static final float IAMGE_HEIGHT = 200; // 水印图片的的高度
private static final float IAMGE_WIDTH = 200; // 水印图片的的宽度
public static void main(String[] args) throws DocumentException, IOException {
// 将pdf文件先加水印然后输出
setWatermark("E:/dataquerywatermark.pdf", "E:/abc.pdf", "水印水印水印");
}
/**
*
* @Description:
* @Title: setWatermark
* @param input 原PDF位置 E:/dataquerywatermark.pdf
* @param out 输出PDF文件的位置 E:/abc.pdf
* @param waterMarkName 文字水印
* @throws DocumentException
* @throws IOException
* @Author 我的花儿
* @DateTime 2019年12月3日 下午2:21:35
*/
public static void setWatermark(String input, String out, String waterMarkName)
throws DocumentException, IOException {
String FONTS_PATH = ItextUtil.class.getResource("/").getPath() + "../../static/web/platform/common/ace/fonts/";
// 创建一个pdf读入流
PdfReader reader = new PdfReader(input);
// 根据一个pdfreader创建一个pdfStamper.用来生成新的pdf.
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(new File(out)));
int total = reader.getNumberOfPages() + 1; // 总页数+1
PdfContentByte pdfContentByte;
BaseFont baseFont = BaseFont.createFont(FONTS_PATH + "msyh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
PdfGState gs = new PdfGState();
// 页数是从1开始的
for (int i = 1; i < total; i++) {
Rectangle pageRect = null;
// 获得pdfstamper在当前页的上层打印内容.也就是说 这些内容会覆盖在原先的pdf内容之上.
pdfContentByte = stamper.getOverContent(i);// 在内容上方加水印
// content = stamper.getUnderContent(i);//在内容下方加水印
gs.setFillOpacity(0.5f); // 透明度设置
pdfContentByte.setGState(gs);
// //文字水印
pdfContentByte.beginText();// 开始写入文本
pdfContentByte.setColorFill(Color.LIGHT_GRAY);
pdfContentByte.setFontAndSize(baseFont, 50);
pdfContentByte.setTextMatrix(70, 200); // 设置字体的输出位置
pdfContentByte.showTextAligned(Element.ALIGN_CENTER, "公司内部文件,请注意保密!", 300, 350, 55);// 要输出的text
// 图片水印,创建一个image对象.
Image image = Image.getInstance("E:/watermark.png");
// //用pdfreader获得当前页字典对象.包含了该页的一些数据.比如该页的坐标轴信息.
// PdfDictionary pdfDictionary = reader.getPageN(i);
// //拿到mediaBox 里面放着该页pdf的大小信息.
// PdfObject pdfObject = pdfDictionary.get(new PdfName("MediaBox"));
// //pdfObject是一个数组对象.里面包含了该页pdf的坐标轴范围.
// PdfArray PdfArray = (PdfArray) pdfObject;
// //设置image对象的输出位置PdfArray.getAsNumber(pa.size()-1).floatValue()
// 是该页pdf坐标轴的y轴的最大值
// image.setAbsolutePosition(0,PdfArray.getAsNumber(PdfArray.size()-1).floatValue()-100);//[0,
// 0, 595.28, 841.88]
float pageHeight = reader.getPageSize(1).getHeight();// 模板高度
float pageWidth = reader.getPageSize(1).getWidth();// 模板宽度
for (int x = 0; x < Math.ceil(pageWidth / IAMGE_WIDTH); x++) {
for (int y = 0; y < Math.ceil(pageHeight / IAMGE_HEIGHT); y++) {
image.scaleToFit(IAMGE_WIDTH, IAMGE_HEIGHT);// 两个参数分别设置长和宽的最大值,但是图片长宽比不变
image.setAbsolutePosition(x * IAMGE_WIDTH, y * IAMGE_HEIGHT);
image.scalePercent(50);// 放大或者缩小图片
// image.scaleAbsolute(200,100);//自定义大小
// image.setRotation(-20);// 旋转 弧度
// image.setRotationDegrees(45);// 旋转 角度
pdfContentByte.addImage(image);
}
}
// 文字水印平铺s
JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
textH = metrics.getHeight();
textW = metrics.stringWidth(label.getText());
pageRect = reader.getPageSizeWithRotation(i);
pdfContentByte.saveState();
pdfContentByte.setGState(gs);
pdfContentByte.beginText();
pdfContentByte.setFontAndSize(baseFont, 20);
int interval = -5;
for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 3) {
for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 2) {
pdfContentByte.setColorFill(Color.LIGHT_GRAY); // 字体颜色
pdfContentByte.showTextAligned(Element.ALIGN_LEFT, "水印文字", width - textW, height - textH, 30);
}
}
// 封面logo
if (i == 1) {
Image imageIndex = Image.getInstance("E:/logo.png");
PdfGState gsIndex = new PdfGState();
gsIndex.setFillOpacity(1f); // 透明度设置
pdfContentByte.setGState(gsIndex);
imageIndex.setAbsolutePosition(30, 725);
imageIndex.scalePercent(80);// 放大或者缩小图片
pdfContentByte.addImage(imageIndex);
}
if (i >= 2) {
// 页眉左侧图片
Image image2 = Image.getInstance("E:/logo-sm.png");
PdfGState gs2 = new PdfGState();
gs2.setFillOpacity(1f); // 透明度设置
pdfContentByte.setGState(gs2);
image2.setAbsolutePosition(30, 770);
image2.scalePercent(80);// 放大或者缩小图片
pdfContentByte.addImage(image2);
// 页眉右侧文字
pdfContentByte.setColorFill(Color.BLACK); // 字体颜色
pdfContentByte.setFontAndSize(baseFont, 10); // 字体以及字体大小
pdfContentByte.showTextAligned(Element.ALIGN_LEFT, "文件编号: 123456789", 380, 795, 0);
pdfContentByte.showTextAligned(Element.ALIGN_LEFT, "生成日期: 2019年12月3日", 380, 775, 0);
// 页眉分割线
Image image3 = Image.getInstance("E:/dashed.png");
PdfGState gs3 = new PdfGState();
gs3.setFillOpacity(1f); // 透明度设置
for (int j = 6; j < 112; j++) {
image3.scaleToFit(3, 3);// 两个参数分别设置长和宽的最大值,但是图片长宽比不变
image3.setAbsolutePosition(j * 5, 755);
image3.scalePercent(80);// 放大或者缩小图片
pdfContentByte.setGState(gs3);
pdfContentByte.addImage(image3);
}
// 页脚
pdfContentByte.setColorFill(Color.BLACK); // 字体颜色
pdfContentByte.setFontAndSize(baseFont, 10); // 字体以及字体大小
int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
pdfContentByte.showTextAligned(Element.ALIGN_CENTER, "第" + i + "页/共" + pageSize + "页", 300, 10, 0);// "第"+i+"页/共"+pageSize+"页"
pdfContentByte.endText();
}
}
stamper.close();
reader.close();
// 删除不带水印文件
File tempfile = new File(input);
if (tempfile.exists()) {
tempfile.delete();
}
}
}