/**
* PDF添加水印
* @param inputFile 你的PDF文件地址
* @param outputFile 添加水印后生成PDF存放的地址
* @param waterMarkName 你的中文水印
* @throws DocumentException
* @throws IOException
*/
public static void addWatermark(String inputFile,String outputFile, String waterMarkName )
throws DocumentException, IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(outputFile)));
// 将pdf文件先加水印然后输出
setWatermark(bos, inputFile, waterMarkName, 16);
}
/**
*
* @param bos输出文件的位置
* @param input原PDF位置
* @param waterMarkName 页脚添加水印
* @param permission 权限码
* @throws DocumentException
* @throws IOException
*/
public static void setWatermark(BufferedOutputStream bos, String input, String waterMarkName, int permission)
throws DocumentException, IOException {
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, bos);
int total = reader.getNumberOfPages() + 1;
// PdfContentByte content;
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
/* PdfGState gs = new PdfGState();
for (int i = 1; i < total; i++) {
//content = stamper.getOverContent(i);// 在内容上方加水印
content = stamper.getUnderContent(i);//在内容下方加水印
gs.setFillOpacity(0.2f);
// content.setGState(gs);
content.beginText();
content.setColorFill(Color.LIGHT_GRAY);
content.setFontAndSize(base, 50);
content.setTextMatrix(70, 200);
content.showTextAligned(Element.ALIGN_CENTER, "仅供预览", 300, 350, 55);
//Image image = Image.getInstance("E:/test/预览.png");
img.setAlignment(Image.LEFT | Image.TEXTWRAP);
img.setBorder(Image.BOX); img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE); img.scaleToFit(100072);//大小
img.setRotationDegrees(-30);//旋转
// image.setAbsolutePosition(200, 206); // set the first background
// // image of the absolute
// image.scaleToFit(200, 200);
// content.addImage(image);
content.setColorFill(Color.BLACK);
content.setFontAndSize(base, 8);
content.showTextAligned(Element.ALIGN_CENTER, "下载时间:" + waterMarkName + "", 300, 10, 0);
content.endText();
}*/
PdfContentByte under;
@SuppressWarnings("unused")
com.lowagie.text.Rectangle pageRect = null;
for (int i = 1; i < total; i++) {
pageRect = stamper.getReader(). getPageSizeWithRotation(i);
// 计算水印X,Y坐标
// float x = pageRect.getWidth()/10;
// float y = pageRect.getHeight()/10-10;
// 获得PDF最顶层
// under = stamper.getOverContent(i);
under = stamper.getUnderContent(i);//在内容下方加水印
under.saveState();
// set Transparency
PdfGState gs = new PdfGState();
// 设置透明度为0.2
// gs.setFillOpacity(0.8f);
gs.setFillOpacity(0.3f);
gs.setStrokeOpacity(0.4f);
under.setGState(gs);
under.restoreState();
under.beginText();
under.setFontAndSize(base, 25);
under.setTextMatrix(30, 30);
under.setColorFill(Color.GRAY);
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 8; x++) {
// 水印文字成45度角倾斜
under.showTextAligned(Element.ALIGN_LEFT , waterMarkName, 100 + 300 * x, 300 * y, 45);
}
}
// 添加水印文字
under.endText();
under.setLineWidth(1f);
under.stroke();
}
stamper.close();
}