public static String waterMark(String inputFile, String waterMarkName) { String newFile = "" ; try { PdfReader reader = new PdfReader(inputFile) ; File input =new File(inputFile) ; String fileName =input.getName() ; String filePath =input.getParent() ; newFile =filePath+ "水印_" +System.currentTimeMillis()+fileName ; System.out.println("newFile:"+newFile) ; PdfStamper stamper = new PdfStamper(reader, new FileOutputStream( newFile)) ; BaseFont base = BaseFont.createFont( "STSong-Light" , "UniGB-UCS2-H" , BaseFont.EMBEDDED) ; Rectangle pageRect = null ; PdfGState gs = new PdfGState() ; gs.setFillOpacity(0.3f) ;// 设置填充字体不透明度为0.3f gs.setStrokeOpacity(0.4f) ; int total = reader.getNumberOfPages() + 1 ; 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()) ; PdfContentByte under ; for (int i = 1 ; i < total; i++) { pageRect = reader.getPageSizeWithRotation(i) ; under = stamper.getOverContent(i) ; under.saveState() ; under.setGState(gs) ; under.beginText() ; under.setFontAndSize(base, 20) ; // 水印文字成30度角倾斜 //你可以随心所欲的改你自己想要的角度 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 ) { under.showTextAligned(Element.ALIGN_LEFT , waterMarkName, width - textW, height - textH, 30) ; // 添加水印文字 under.endText() ; //说三遍 //一定不要忘记关闭流 //一定不要忘记关闭流 //一定不要忘记关闭流 stamper.close() ; reader.close() ; } catch (Exception e) { e.printStackTrace() ; return newFile ; * 测试方法-主入口 public static void main(String [] args) { waterMark('F"/XXX','一枚coding小姐姐! [] (https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a309bd028c274fa6a4626398050b5187~tplv-k3u1fbpfcp-zoom-1.image)') ; 一枚coding小姐姐 终极软件攻城狮
粉丝