File file = new File(outFilePath + "filename.pdf");
String DEST = outFilePath + "filename_water.pdf";
FileInputStream input1 = new FileInputStream(file);
FileOutputStream output2 = new FileOutputStream(new File(DEST));
stringWaterMark(input1, output2, "浮水印測試", 2, 3, 0.15f,45, 84,BaseColor.BLACK);
/* 斜角排列、多個重複的花式文字浮水印
* @param input 需要加水印的PDF讀取輸入流
* @param output 輸出生成PDF的輸出流
* @param waterMarkString 浮水印字
* @param xAmout x軸重複數量
* @param yAmout y軸重複數量
* @param opacity 水印透明度
* @param rotation 水印文字旋轉角度,一般為45度角
* @param waterMarkFontSize 水印字型大小
* @param color 水印字型顏色
*/
public static void stringWaterMark(InputStream input, OutputStream output, String waterMarkString, int xAmout, int yAmout, float opacity, float rotation, int waterMarkFontSize, BaseColor color) {
try {
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, output);
// 新增中文字型
String chMingliu1FontPath = "c:\\Windows\\Fonts\\mingliu.ttc,0";//windows內建的新細明體
BaseFont baseFont = BaseFont.createFont(chMingliu1FontPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
int total = reader.getNumberOfPages() + 1;
PdfContentByte over;
// 給每一頁面加浮水印
for (int i = 1; i < total; i++) {
Rectangle pageRect = stamper.getReader().getPageSizeWithRotation(i);
// 計算水印每個單位距離X,Y
float x = pageRect.getWidth() / xAmout;
float y = pageRect.getHeight() / yAmout;
over = stamper.getOverContent(i);
PdfGState gs = new PdfGState();
// 設定透明度為
gs.setFillOpacity(opacity);
over.setGState(gs);
over.saveState();
over.beginText();
over.setColorFill(color);
over.setFontAndSize(baseFont, waterMarkFontSize);
for (int n = 0; n < xAmout + 1; n++) {
for (int m = 0; m < yAmout + 1; m++) {
over.showTextAligned(Element.ALIGN_CENTER, waterMarkString, x * n, y * m, rotation);
}
}
over.endText();
}
stamper.close();
} catch (Exception e) {
System.out.println("PDF error "+e.getMessage());
}
}
沒有留言:
張貼留言