1.整合jar:
itext-asian-5.2.0.jar,itextpdf-5.5.10.jar,iTextAsianCmaps.jar
下载:itext的整合jar包
2.使用方法:
public void ShowTextAligned(int alignment, String text, float x,float y, float rotation)
参数 参数说明:
alignment 左、右、居中(ALIGN_CENTER, ALIGN_RIGHT or ALIGN_LEFT)
text 要输出的文本
x 文本输入的X坐标
y 文本输入的Y坐标
rotation 文本的旋转角度
/** * * @param output 生成文件的路径 * @param inputPath 原文件的路径 * @param wartermark 水印内容 * @return */ public static boolean createMark(String output, String inputPath, String wartermark){ boolean flag = false; PdfReader reader = null; PdfStamper stamper = null; Rectangle pageRect = null; try { reader = new PdfReader(inputPath); stamper = new PdfStamper(reader, new FileOutputStream(output)); int total = reader.getNumberOfPages() + 1; PdfContentByte content; BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED); PdfGState gs = new PdfGState(); for (int j = 1; j < total; j++) { pageRect = stamper.getReader().getPageSizeWithRotation(j); // 计算水印X,Y坐标 float x = 0; float y = 0; content = stamper.getOverContent(j);// 在内容上方加水印 gs.setFillOpacity(1.f);// 设置透明度 content.setGState(gs); content.beginText(); content.setColorFill(BaseColor.LIGHT_GRAY); content.setFontAndSize(base, 15); content.setTextMatrix(70, 200); while(x<pageRect.getWidth()){ while(y < pageRect.getHeight()){ // 水印文字成45度角倾斜 content.showTextAligned(Element.ALIGN_CENTER, wartermark, x,y, 55); y += pageRect.getHeight()/20; } y = 0; x += pageRect.getWidth()/8; } x = 0; content.endText(); } stamper.close(); System.out.println("添加水印成功。。。。。。。。。。。。。。。"); flag=true; } catch (Exception e) { e.printStackTrace(); } return flag; }