基于itext实现的pdf水印
项目需要,实现了一个基于itext的pdf水印功能,在此重点强调水印图片必须是事先处理好的背景透明及透明度适当的图片,否则水印效果不佳甚至无效果(背景不透明的话,会遮盖PDF正常内容),具体基于java的图片处理,请参见本人另一篇博文java的图片透明处理:
/** * * @Title: createWaterMarkSpread2PDF * @Description: 针对PDF添加水印图片,并根据间隙计算,平铺 居中显示 * @param srcFilePath 源文件 * @param savePath 保存文件 * @param waterMarkPath 水印图片 * @param spaceX 横向间隙 * @param spaceY 纵向间隙 * @return * @throws IOException * @throws DocumentException */ public static void createWaterMarkSpread2PDF(String srcFilePath, String savePath, String waterMarkPath,float spaceX,float spaceY) throws IOException, DocumentException{ PdfReader pdfReader = null; PdfStamper pdfStamper = null; try{ pdfReader = new PdfReader(srcFilePath); pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(savePath));; int pageCount = pdfReader.getNumberOfPages()+1;//获取PDF页数 Image image = Image.getInstance(waterMarkPath); Rectangle size = pdfReader.getPageSize(1); float pdfY = size.top();//PDF页面高度 float pdfX = size.right();//PDF页面宽度 Dimension dim = ImageUtil.getDim4Image(waterMarkPath); PageSpreadSize pss = getPageSpreadSize(size, dim, spaceX, spaceY); PdfContentByte content=null; float heightWithSpace = (float)dim.getHeight()+(Float.isNaN(spaceY)||spaceY<=0?0:spaceY/2); float widthWithSpace = (float)dim.getWidth()+(Float.isNaN(spaceX)||spaceX<=0?0:spaceX/2); boolean isSpread = isImageSpread(pss);//是否平铺 //起始位置信息 float startX = isSpread?(pdfX-widthWithSpace*pss.getSizeX())/2:(float)(pdfX/2-dim.getWidth()/2); float startY = isSpread?pdfY -(pdfY-heightWithSpace*pss.getSizeY())/2:((float)(pdfY/2-dim.getHeight()/2)); //给每页增加水印 for (int i = 1; i < pageCount; i++) { content = pdfStamper.getOverContent(i); float posY = pdfY;//Y坐标绝对路径 if(!isSpread){ image.setAbsolutePosition(startX, startY); content.addImage(image); } else{ //行 for(int pi=1; pi<=pss.getSizeY(); pi++){ posY = startY - pi*heightWithSpace; float posX=0f; //X坐标绝对路径 //列 for(int py=1; py<=pss.getSizeX(); py++){ posX = startX+(py-1)*widthWithSpace; image.setAbsolutePosition(posX, posY); content.addImage(image); } } } content = null;//便于及时回收 } }finally{ if(pdfStamper!=null){ pdfStamper.close(); pdfStamper = null; pdfReader = null; } } }