itext添加水印

/**
 * 图片水印
 * @param pdfBty
 * @param imagePath
 * @return
 * @throws Exception
 */
public  byte[] imageWatermark(byte[] pdfBty, String imagePath) throws Exception {
   PdfReader reader=null;
   PdfStamper stamp=null;
   try{

      reader = new PdfReader(pdfBty);
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      stamp = new PdfStamper(reader, out);
      PdfGState gs1 = new PdfGState();
      gs1.setFillOpacity(1f);

      Image image = Image.getInstance(IOUtils.toByteArray(new FileInputStream(imagePath)));
      int n = reader.getNumberOfPages();
      for (int i = 1; i <= n; i++) {
         PdfContentByte pdfContentByte = stamp.getUnderContent(i);
         pdfContentByte.setGState(gs1);
         /* 设置图片的位置 */
         image.setAbsolutePosition(0, 0);
         /* 设置图片的大小 (A4)*/
         image.scaleAbsolute(595, 842);

         pdfContentByte.addImage(image);
      }

      stamp.close();
      return out.toByteArray();
       }finally{
      reader.close();
   }

}

/**
    * 倾斜文字水印
    * @param pdfBty
    * @param waterMarkName
    * @return
    * @throws Exception
    */
   public  byte[] setWaterMark(byte[] pdfBty, String waterMarkName) throws Exception {
      int interval = -5;
      ByteArrayOutputStream out = null;
      PdfReader pdfReader = null;
      PdfStamper pdfStamper = null;
      try {
         pdfReader = new PdfReader(pdfBty);
         out = new ByteArrayOutputStream();
         pdfStamper = new PdfStamper(pdfReader, out);

         int total = pdfReader.getNumberOfPages() + 1;//获取PDF的总页数
         Rectangle pageRect = null;
         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 waterContent = null;
         // 设置字体
         BaseFont basefont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
         PdfGState gs = new PdfGState();
         //透明度
         gs.setFillOpacity(0.5f);// 设置透明度为0.2
         for (int i = 1; i < total; i++) {
            pageRect=pdfReader.getPageSizeWithRotation(i);//获取页
            waterContent = pdfStamper.getUnderContent(i);//在内容上方加水印

            waterContent.setGState(gs);
            //开始写入文本
            waterContent.beginText();
            waterContent.setColorFill(BaseColor.ORANGE);
            waterContent.setFontAndSize(basefont, 13);
            waterContent.setTextMatrix(0, 0);
            // 计算水印X,Y坐标
            float x = pageRect.getWidth() / 2;
            float y = pageRect.getHeight() / 2;
            for (int height = interval + textH; height < pageRect.getHeight();
                height = height + textH*8) {
               for (int width = interval + textW; width < pageRect.getWidth() + textW;
                   width = width + textW) {
                  waterContent.showTextAligned(Element.ALIGN_LEFT
                        , waterMarkName, width - textW,
                        height - textH, 45);
               }
            }

            waterContent.endText();
            pdfStamper.close();
            return out.toByteArray();
         }

      } finally {
         if (pdfReader != null)
            pdfReader.close();
      }

      return pdfBty;
   }
public static void main(String[] args) {
   System.out.println("picc\r\nlife");

   File pdfFile = new File("E://test.pdf");
   FileInputStream profitfis = null;
   byte[] pdfByte = null;
   byte[] outByte = null;
   try {
      profitfis = new FileInputStream(pdfFile);
      pdfByte = IOUtils.toByteArray(profitfis);
      PrintPdfUtil util = new PrintPdfUtil();
      util.setWaterMark(pdfByte,"水印文字");
   } catch (IOException e) {
      e.printStackTrace();
   } catch (Exception e) {
      e.printStackTrace();
   }

   ByteArrayOutputStream out = new ByteArrayOutputStream();
   PdfReader pr = null;
   try {
      pr = new PdfReader(outByte);
      PdfStamper ps = new PdfStamper(pr, out);
      AcroFields as = ps.getAcroFields();
      Map<String, Item> fields = as.getFields();
      if (fields != null && fields.entrySet() != null) {
         for (Map.Entry<String, Item> entry : fields.entrySet()) {
            as.setField(entry.getKey(), "");
         }
      }

      ps.setFormFlattening(true);
      ps.close();

      File file = new File("E://myWater.pdf");
      File dir = file.getParentFile();
      if (!dir.exists()) {
         dir.mkdirs();
      }
      file.createNewFile();
      FileOutputStream fos = new FileOutputStream("E://myWater.pdf");
      fos.write(out.toByteArray());
      fos.flush();
      fos.close();
   } catch (IOException e) {
      e.printStackTrace();
   } catch (DocumentException e) {
      e.printStackTrace();
   }
}

猜你喜欢

转载自blog.csdn.net/flyer_tang/article/details/80269772