iText-为PDF添加水印

阅读更多

 

 private static void addWatermark(PdfStamper stamper, Rectangle pageRectangle, int waterMarkCount,
      String waterMarkName) {
    PdfContentByte content;
    BaseFont base = null;
    try {
      //设置字体
      base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

//计算水印X,Y坐标
    float x = pageRectangle.getWidth() / 2;
    float y = pageRectangle.getHeight() / 2;
    for (int i = 1; i < waterMarkCount + 1; i++) {
  
      content = stamper.getOverContent(i);//获得PDF最顶层
      content.saveState();
      // set Transparency
      PdfGState gs = new PdfGState();
      gs.setFillOpacity(0.2f);//设置透明度为0.2
      content.setGState(gs);

      
      content.beginText();
      content.setColorFill(BaseColor.GRAY);
      content.setFontAndSize(base, 40);
      content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, x, y, 35);//水印文字成35度角倾斜
      content.endText();
      content.beginText();
      
      content.setColorFill(BaseColor.GRAY);
      content.setFontAndSize(base, 30);
      String seeAttached="(See attached digital certificate)";
      content.showTextAligned(Element.ALIGN_CENTER, seeAttached, x, y-42, 35);
      content.endText();

      content.restoreState();//注意这里必须调用一次restoreState 否则设置无效

    }
  }

你可能感兴趣的:(iText-为PDF添加水印)