java 實現 PDF 加水印功能


使用java代碼實現給PDF加水印的功能

  • 首先導入所需要的依賴
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
  • java 代碼實現
     /**
     * @param inputFile 你的PDF文件地址
     * @param outputFile 添加水印后生成PDF存放的地址
     * @param waterMarkName 你的水印
     * @return
     */
      public static boolean 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.NOT_EMBEDDED);// 使用系統字體
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
                pageRect = stamper.getReader().
                        getPageSizeWithRotation(i);
                // 計算水印X,Y坐標
                float x = pageRect.getWidth()/10;
                float y = pageRect.getHeight()/10-10;
                // 獲得PDF最頂層
                under = stamper.getOverContent(i);
                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 設置透明度為0.2
                gs.setFillOpacity(1.f);
                under.setGState(gs);
                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, 60);
                under.setColorFill(BaseColor.ORANGE);

                // 水印文字成45度角傾斜
                under.showTextAligned(Element.ALIGN_CENTER
                        , waterMarkName, x,
                        y, 55);
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM