itext之pdf導出添加水印Java工具類


import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfFileExportUtil {

    private static Font pdf8Font = null;

    private static Font pdf20Font = null;

    /**
     * 
     * 設置PDF創建者信息
     * 
     * @param pdfDocument
     */

    public static Document setCreatorInfo(Document pdfDocument) {

        if (pdfDocument == null) {

            return null;

        }

        // 文檔屬性
        pdfDocument.addTitle("北京XX科技有限公司綜合分析PDF文檔");
        pdfDocument.addAuthor("北京XX科技有限公司");
        pdfDocument.addSubject("XX分析頁");
        pdfDocument.addKeywords("綜合分析");// 文檔關鍵字信息
        pdfDocument.addCreator("XX數據平台");// 應用程序名稱
        return pdfDocument;
    }

    /**
     * 
     * 獲取中文字符集且是8號字體,常用作表格內容的字體格式
     * 
     * @param fullFilePath
     */

    public static Font getChinese8Font() throws DocumentException, IOException {

        if (pdf8Font == null) {

            // 設置中文字體和字體樣式
            BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            pdf8Font = new Font(bfChinese, 8, Font.NORMAL);

        }

        return pdf8Font;
    }

    /**
     * 
     * 獲取中文字符集且是8號字體,常用作文字水印信息
     * 
     * @param fullFilePath
     */

    public static Font getChinese20Font() throws DocumentException, IOException {

        if (pdf20Font == null) {

            // 設置中文字體和字體樣式
            BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                    "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            pdf20Font = new Font(bfChinese);
            pdf20Font.setSize(5);
        }

        return pdf20Font;
    }

    /**
     * 
     * 設置成只讀權限
     * 
     * @param pdfWriter
     */

    public static PdfWriter setReadOnlyPDFFile(PdfWriter pdfWriter)
            throws DocumentException {

        pdfWriter.setEncryption(null, null, PdfWriter.ALLOW_PRINTING,
                PdfWriter.STANDARD_ENCRYPTION_128);

        return pdfWriter;
    }

    /**
     * 
     * 變更一個圖片對象的展示位置和角度信息
     * 
     * @param waterMarkImage
     * 
     * @param xPosition
     * 
     * @param yPosition
     * 
     * @return
     */

    public static Image getWaterMarkImage(Image waterMarkImage,
            float xPosition, float yPosition) {

        waterMarkImage.setAbsolutePosition(xPosition, yPosition);// 坐標

        waterMarkImage.setRotation(-20);// 旋轉 弧度

        waterMarkImage.setRotationDegrees(-45);// 旋轉 角度

        waterMarkImage.scalePercent(100);// 依照比例縮放
        return waterMarkImage;
    }

    /**
     * 
     * 為PDF分頁時創建添加文本水印的事件信息
     */

    public class TextWaterMarkPdfPageEvent extends PdfPageEventHelper {

        private String waterMarkText;

        public TextWaterMarkPdfPageEvent(String waterMarkText) {

            this.waterMarkText = waterMarkText;

        }

        public void onEndPage(PdfWriter writer, Document document) {

            try {

                float pageWidth = document.right() + document.left();// 獲取pdf內容正文頁面寬度

                float pageHeight = document.top() + document.bottom();// 獲取pdf內容正文頁面高度

                // 設置水印字體格式

                Font waterMarkFont = PdfFileExportUtil.getChinese20Font();

                PdfContentByte waterMarkPdfContent = writer.getDirectContent();//決定了水印圖層高低
                Phrase phrase = new Phrase(waterMarkText, waterMarkFont);
                for(int i = 0 ; i < 100; i ++){
                    for(int j = 0 ; j < 20 ; j ++ ){
                        ColumnText.showTextAligned(waterMarkPdfContent,Element.ALIGN_CENTER, phrase,pageWidth * 0.2f * j, pageHeight * 0.08f * i, 45);
                    }
                }

            } catch (DocumentException de) {

                de.printStackTrace();

                System.err.println("pdf watermark font:" + de.getMessage());

            } catch (IOException de) {

                de.printStackTrace();

                System.err.println("pdf watermark font:" + de.getMessage());

            }

        }

    }

    /**
     * 
     * 為PDF分頁時創建添加圖片水印的事件信息
     */

    public class PictureWaterMarkPdfPageEvent extends PdfPageEventHelper {

        private String waterMarkFullFilePath;

        private Image waterMarkImage;

        public PictureWaterMarkPdfPageEvent(String waterMarkFullFilePath) {

            this.waterMarkFullFilePath = waterMarkFullFilePath;

        }

        public void onEndPage(PdfWriter writer, Document document) {

            try {

                float pageWidth = document.right() + document.left();// 獲取pdf內容正文頁面寬度

                float pageHeight = document.top() + document.bottom();// 獲取pdf內容正文頁面高度

                PdfContentByte waterMarkPdfContent = writer.getDirectContent();

                // 僅設置一個圖片實例對象,整個PDF文檔只應用一個圖片對象,極大減少因為增加圖片水印導致PDF文檔大小增加

                if (waterMarkImage == null) {

                    waterMarkImage = Image.getInstance(waterMarkFullFilePath);

                }
                // 添加水印圖片,文檔正文內容采用橫向三列,豎向兩列模式增加圖片水印
                for(int i = 0 ; i < 100; i ++){
                    for(int j = 0 ; j < 4 ; j ++ ){
                        waterMarkPdfContent.addImage(getWaterMarkImage(waterMarkImage,pageWidth * 0.3f * j , pageHeight * 0.05f * i));
                    }
                }

                PdfGState gs = new PdfGState();
                gs.setFillOpacity(0.8f);// 設置透明度為0.2
                gs.setStrokeOpacity(0.8f);
                gs.setOverPrintStroking(true);
                waterMarkPdfContent.setGState(gs);

            } catch (DocumentException de) {

                de.printStackTrace();

                System.err.println("pdf watermark font:" + de.getMessage());

            } catch (IOException de) {

                de.printStackTrace();

                System.err.println("pdf watermark font:" + de.getMessage());

            }

        }

    }

    /**
     * 
     * 為PDF分頁時創建添加header和footer信息的事件信息
     */

    class HeadFootInfoPdfPageEvent extends PdfPageEventHelper {

        public HeadFootInfoPdfPageEvent() {

        }

        public void onEndPage(PdfWriter writer, Document document) {

            try {

                PdfContentByte headAndFootPdfContent = writer
                        .getDirectContent();
                
                headAndFootPdfContent.saveState();

                headAndFootPdfContent.beginText();

                BaseFont bfChinese = BaseFont.createFont("STSong-Light",
                        "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

                headAndFootPdfContent.setFontAndSize(bfChinese, 10);

                // 文檔頁頭信息設置

                float x = document.top(-20);

                // 頁頭信息左面

                headAndFootPdfContent.showTextAligned(
                        PdfContentByte.ALIGN_LEFT,

                        "綜合分析",

                        document.left(), x, 0);

                // 頁頭信息中間

                headAndFootPdfContent.showTextAligned(
                        PdfContentByte.ALIGN_CENTER,

                        "第" + writer.getPageNumber() + "頁",

                        (document.right() + document.left()) / 2,

                        x, 0);

                // 頁頭信息右面

                headAndFootPdfContent.showTextAligned(
                        PdfContentByte.ALIGN_RIGHT,

                        "北京XX科技有限公司",

                        document.right(), x, 0);

                // 文檔頁腳信息設置

                float y = document.bottom(-20);

                // 頁腳信息左面

                headAndFootPdfContent.showTextAligned(
                        PdfContentByte.ALIGN_LEFT,

                        "--",

                        document.left(), y, 0);

                // 頁腳信息中間

                headAndFootPdfContent.showTextAligned(
                        PdfContentByte.ALIGN_CENTER,

                        "-",

                        (document.right() + document.left()) / 2,

                        y, 0);

                // 頁腳信息右面

                headAndFootPdfContent.showTextAligned(
                        PdfContentByte.ALIGN_RIGHT,

                        "--",

                        document.right(), y, 0);

                headAndFootPdfContent.endText();

                headAndFootPdfContent.restoreState();

            } catch (DocumentException de) {

                de.printStackTrace();

                System.err.println("pdf watermark font:" + de.getMessage());

            } catch (IOException de) {

                de.printStackTrace();

                System.err.println("pdf watermark font:" + de.getMessage());

            }

        }

    }
}

使用方法:

            PdfFileExportUtil pdfFileExportUtil = new PdfFileExportUtil();
            pdfWriter.setPageEvent(pdfFileExportUtil.new PictureWaterMarkPdfPageEvent(basePath+"/images/xxx.png"));

 


免責聲明!

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



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