java实现给pdf文件加水印!
作者:互联网
给pdf文档加水印!
public static void waterMark(String inputFile, String outputFile, String waterMarkName) { try { PdfReader reader = new PdfReader(inputFile); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream( outputFile)); BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); Rectangle pageRect = null; PdfGState gs = new PdfGState(); gs.setFillOpacity(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++) { under = stamper.getOverContent(i);// 在内容上方加水印 //content = stamper.getUnderContent(i);//在内容下方加水印 gs.setFillOpacity(0.2f); // content.setGState(gs); under.beginText(); under.setFontAndSize(base, 50); under.setTextMatrix(70, 200); under.showTextAligned(Element.ALIGN_CENTER, "测试水印!", 300,350, 55); under.endText(); } //一定不要忘记关闭流 stamper.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } }
标签:java,reader,new,label,stamper,加水,under,pdf,gs 来源: https://www.cnblogs.com/sjzxs/p/11189913.html