iText 5.x 生成PDF文件(含List分批處理數據)


前言

剛入職一家新公司,因為項目還沒開展,領導安排了小功能開發,給我了兩個PDF文件,有logo、條形碼、以及不確定有多少內容的表格、還有固定的地步落款信息。還是挺多內容的。我也是一頓百度認識了 iText插件,看其他大佬說這是還是挺牛的。(我只是簡單的會用了,還要再接再厲啊)廢話不說了,先上效果圖看看是不是你要的效果。(分批處理數據在最底部)

成品圖,數據會打上馬賽克喲。

下面2張圖是一個PDF文件:

 上硬菜,jar包依賴

<!-- ******************** 生成pdf要用的jar start ******************** -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>
        <!-- pdf輸出中文要用的jar -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- 設置pdf的打開密碼要用的jar 【暫時沒有用到】 -->
        <!--<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.54</version>
        </dependency>-->
<!-- ******************** 生成pdf要用的jar end ******************** -->

封裝的工具類:PdfFUtil,內含頁碼方法import com.itextpdf.text.*;import com.itextpdf.text.pdf.*;

import java.io.IOException;

public class PdfFUtil {

    // 最大寬度
    private static int maxWidth = 520;

/**------------------------創建表格單元格的方法start----------------------------*/
    /**
     * 創建單元格(指定字體)
     *
     * @param value
     * @param font
     * @return
     */
    public static PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
        cell.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 創建單元格(指定字體、設置單元格高度)
     *
     * @param value
     * @param font
     * @return 申請事由——這行使用的方法
     */
    public static PdfPCell createCell(String value, Font font, float f) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        cell.setFixedHeight(f); // 設置表格中的單行高度
        return cell;
    }

    /**
     * 創建單元格(指定字體、水平局左/中/右)
     *
     * @param value
     * @param font
     * @param align
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
        cell.setHorizontalAlignment(align); //水平居中
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 創建單元格(指定字體、水平局左/中/右、單元格跨x列合並)
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @return
     */
    public PdfPCell createCell(String value, Font font, int align, int colspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
        cell.setHorizontalAlignment(align); //水平居中
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 創建單元格(指定字體、水平居..、單元格跨x列合並、設置單元格內邊距)
     *
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            /*cell.setPaddingTop(15.0f);
            cell.setPaddingBottom(8.0f);*/
            cell.setPaddingTop(10.0f);
            cell.setPaddingBottom(7.0f);
        } else if (boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(0.0f);
            cell.setPaddingBottom(15.0f);
        }
        return cell;
    }

    /**
     * 創建單元格(指定字體、水平..、邊框寬度:0表示無邊框、內邊距)
     *
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        return cell;
    }
/**------------------------創建表格單元格的方法end----------------------------*/


/**--------------------------創建表格的方法start----------------------------*/
    /**
     * 創建默認列寬,指定列數、水平(居中、右、左)的表格
     *
     * @param colNumber
     * @param align
     * @return
     */
    public PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 創建指定列寬、列數的表格
     *
     * @param widths
     * @return
     */
    public static PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 創建空白的表格
     *
     * @return
     */
    public PdfPTable createBlankTable() throws IOException, DocumentException {
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font keyfont = new Font(bfChinese, 10, Font.BOLD);
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorder(0);
        table.addCell(createCell("", keyfont));
        table.setSpacingAfter(20.0f);
        table.setSpacingBefore(20.0f);
        return table;
    }
/**--------------------------創建表格的方法end----------------------------*/

/** --------------------------頁碼方法start----------------------------*/
public static void onEndPage(PdfWriter writer, Document document) throws IOException, DocumentException { PdfContentByte cb = writer.getDirectContent(); PdfTemplate tpl; // 頁碼模板用來固定顯示數據 BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); tpl = writer.getDirectContent().createTemplate(100, 100); cb.saveState(); String text = "第" + writer.getPageNumber() + "頁"; cb.beginText(); cb.setFontAndSize(bfChinese, 8); cb.setTextMatrix(480, 35);//定位“第x頁” 在具體的頁面調試時候需要更改這xy的坐標 cb.showText(text); cb.endText(); //** 創建以及固定顯示總頁數的位置 cb.addTemplate(tpl, 283, 10);//定位“y頁” 在具體的頁面調試時候需要更改這xy的坐標 cb.stroke(); cb.restoreState(); cb.closePath(); } /**--------------------------頁碼方法end----------------------------*/

對應第一張的PDF文件,新建java業務類 PdfReport_BX,內含字體常量設置。

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PdfReport_BX {

    public static void pdf() throws Exception {
        try {
            //TODO 1.新建document對象
            Document document = new Document(PageSize.A5.rotate());// 建立一個Document對象

            //TODO 2.建立一個書寫器(Writer)與document對象關聯
            File file = new File("D:\\BXD.pdf"); //修改你要生成PDF的位置路徑
            file.createNewFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            //writer.setPageEvent(new Watermark("HELLO WORLD"));// 水印

            //TODO 3.打開文檔
            document.open();

            //TODO 4.向文檔中添加內容
            new PdfReport_BX().generatePDF(document,writer); // 內容添加的方法

            //TODO 5.關閉文檔
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 生成PDF文件
    public void generatePDF(Document document,PdfWriter writer) throws Exception {

        // 添加圖片
        Image image1 = Image.getInstance("D:/pdf/logo.png");//修改你自己本地的logo圖片
        image1.setAlignment(Image.ALIGN_LEFT);
        image1.scalePercent(85); //依照比例縮放

        PdfContentByte cd = writer.getDirectContent();
        Barcode128 code128 = new Barcode128();
        code128.setCodeType(code128.CODE128);
        code128.setCode("12312312312");
        code128.setBarHeight(28);
        code128.setFont(null); //設置為空,條形碼下方的數字就沒有了
        Image image2 = code128.createImageWithBarcode(cd,null,null);
        image2.setAlignment(Image.ALIGN_RIGHT);
        image2.scalePercent(90); //依照比例縮放
        image2.setAbsolutePosition(435,340);// x、y軸坐標

        //todo 標題
        Paragraph paragraph = new Paragraph("境內差旅報銷", titlefont_16);
        paragraph.setAlignment(1); //設置文字居中 0靠左   1,居中     2,靠右
        paragraph.setIndentationLeft(12); //設置左縮進
        paragraph.setIndentationRight(12); //設置右縮進
        paragraph.setFirstLineIndent(24); //設置首行縮進
        paragraph.setLeading(20f); //行間距
        paragraph.setSpacingBefore(5f); //設置段落上空白
        paragraph.setSpacingAfter(10f); //設置段落下空白

        //todo 第一行
        PdfPTable table_0 = PdfFUtil.createTable(new float[] { 75, 110, 75, 140 });
        table_0.addCell(PdfFUtil.createCell("xxxxxx:", textfont_10, Element.ALIGN_CENTER, 1, false));
        table_0.addCell(PdfFUtil.createCell("xxxxxx", underlinefont_10, Element.ALIGN_LEFT, 1, false));
        table_0.addCell(PdfFUtil.createCell("xxxxxx:", textfont_10, Element.ALIGN_CENTER, 1, false));
        table_0.addCell(PdfFUtil.createCell("xxxxxx ", underlinefont_10, Element.ALIGN_LEFT, 1, false));

        PdfPTable table_1 = PdfFUtil.createTable(new float[] { 75, 110, 75, 140 });
        table_1.addCell(PdfFUtil.createCell("xxxxxx: ", textfont_10, Element.ALIGN_CENTER, 1, false));
        table_1.addCell(PdfFUtil.createCell("xxxxxx", underlinefont_10, Element.ALIGN_LEFT, 1, false));
        table_1.addCell(PdfFUtil.createCell("", textfont_10, Element.ALIGN_CENTER, 1, false));
        table_1.addCell(PdfFUtil.createCell("", textfont_10, Element.ALIGN_LEFT, 1, false));

        // 表格
        PdfPTable table = PdfFUtil.createTable(new float[] { 75, 110, 75, 140 });
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx, textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));
        table.addCell(PdfFUtil.createCell("xxxxxx", textfont_10));

        PdfPTable table_2 = PdfFUtil.createTable(new float[] { 75, 325});
        table_2.addCell(PdfFUtil.createCell("申請事由", textfont_10,40f));
        table_2.addCell(PdfFUtil.createCell("xxxxxx", textfont_10,40f));
        //表格下的落款——xxxxxx、打印時間
        PdfPTable table_3 = PdfFUtil.createTable(new float[] { 75, 325});
        table_3.addCell(PdfFUtil.createCell("xxxxxx", textfont_10, Element.ALIGN_LEFT, 1, false));
        String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        table_3.addCell(PdfFUtil.createCell("打印時間: "+sdf, textfont_10, Element.ALIGN_RIGHT, 1, false));

        document.add(image1); // logo
        document.add(image2); // 條形碼
        document.add(paragraph); // 標題
        document.add(table_0); // 顯示第一行
        document.add(table_1); // 顯示第二行
        document.add(table); //表格數據
        document.add(table_2); //表格的最后一行
        document.add(table_3); //表格下面的落款

    }

/************************* 全局變量 start *************************/
// 定義全局的字體靜態變量
private static Font titlefont_16;
    private static Font titlefontnormal_16;
    private static Font headfont_14;
    private static Font headfontnormal_14;
    private static Font headfont_12;
    private static Font headfontnormal_12;
    private static Font keyfont_10;
    private static Font textfont_10;
    private static Font underlinefont_10;

    // 靜態代碼塊
    static {
        try {
            // 不同字體(這里定義為同一種字體:包含不同字號、不同style)
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            titlefont_16 = new Font(bfChinese, 16, Font.BOLD);
            headfont_14 = new Font(bfChinese, 14, Font.BOLD);
            headfont_12 = new Font(bfChinese, 12, Font.BOLD);
            keyfont_10 = new Font(bfChinese, 10, Font.BOLD);

            titlefontnormal_16 = new Font(bfChinese, 16, Font.NORMAL);
            headfontnormal_14 = new Font(bfChinese, 14, Font.NORMAL);
            headfontnormal_12 = new Font(bfChinese, 12, Font.NORMAL);
            textfont_10 = new Font(bfChinese, 10, Font.NORMAL);
            underlinefont_10 = new Font(bfChinese, 10, Font.UNDERLINE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/************************* 全局變量 end *************************/
}

新建 PdfReport_BXSP 類,對應第二個PDF文件。

這個PDF文件中,logo、條形碼、標題、以及第一、二行、表格的第一行、表格下面的落款、打印時間,每一頁都會存在。只有表格內容因總數據量變化而確定生成幾頁。我這里傳的數據是 List<User>的對象,把公共部分抽取出來,然后采用了 list 分批處理數據的辦法(最后附上 list 分批處理的例子)。此處是每頁顯示9條數據。

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class PdfReport_BXSP {

    public static void pdf(List<User> dataList) throws Exception {
        try {
            // 1.新建document對象
            Document document = new Document(PageSize.A5.rotate());// 建立一個Document對象

            // 2.建立一個書寫器(Writer)與document對象關聯
            File file = new File("D:\\BXDSP.pdf");
            file.createNewFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            //writer.setPageEvent(new Watermark("HELLO WORLD"));// 水印 

            // 3.打開文檔
            document.open();

            // 4.向文檔中添加內容
            new PdfReport_BXSP().generatePDF(document,writer,dataList);

            // 5.關閉文檔
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 生成PDF文件
    public void generatePDF(Document document,PdfWriter writer,List<User> dataList) throws Exception {

        int j = 0;
        String sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //分批處理
        if (null != dataList && dataList.size() > 0) {
            int pointsDataLimit = 9;//限制條數(每頁顯示條數)
            Integer size = dataList.size();
            //判斷是否有必要分批
            if (pointsDataLimit < size) {
                int part = size / pointsDataLimit;//分批數(分幾頁)
                for (int i = 0; i < part; i++) {
                    document.newPage();
                    /* 引入頭部 */
                    header(document, writer);
                    //todo 表格內容填充
                    PdfPTable table = tbPublic();
                    List<User> listPage = dataList.subList(0, pointsDataLimit);
                    for (User user : listPage) {
                        table.addCell(PdfFUtil.createCell(user.getNickname(), textfont_10, Element.ALIGN_LEFT));
                        table.addCell(PdfFUtil.createCell(user.getUsername(), textfont_10, Element.ALIGN_LEFT));
                        table.addCell(PdfFUtil.createCell(user.getRemarks(), textfont_10, Element.ALIGN_LEFT));
                        table.addCell(PdfFUtil.createCell(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                                  .format(user.getCreateTime()), textfont_10, Element.ALIGN_LEFT)); }
//剔除 dataList.subList(0, pointsDataLimit).clear(); document.add(table); //表格數據 /* 引入底部 */ footer(document,sdf); PdfFUtil.onEndPage(writer,document); //當前頁碼 } if (!dataList.isEmpty()) { List<User> listPage = dataList.subList(0, dataList.size()); document.newPage(); /* 引入頭部 */ header(document, writer); PdfPTable table = tbPublic(); for (User user : listPage) { //表示最后剩下的數據 table.addCell(PdfFUtil.createCell(user.getNickname(), textfont_10, Element.ALIGN_LEFT)); table.addCell(PdfFUtil.createCell(user.getUsername(), textfont_10, Element.ALIGN_LEFT)); table.addCell(PdfFUtil.createCell(user.getRemarks(), textfont_10, Element.ALIGN_LEFT)); table.addCell(PdfFUtil.createCell(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                                 .format(user.getCreateTime()), textfont_10, Element.ALIGN_LEFT)); } document.add(table);
//表格數據 /* 引入底部 */ footer(document,sdf); PdfFUtil.onEndPage(writer,document); //當前頁碼 } } else { List<User> listPage = dataList.subList(0, dataList.size()); document.newPage(); /* 引入頭部 */ header(document, writer); PdfPTable table = tbPublic(); for (User user : listPage) { //表示最后剩下的數據 table.addCell(PdfFUtil.createCell(user.getNickname(), textfont_10, Element.ALIGN_LEFT)); table.addCell(PdfFUtil.createCell(user.getUsername(), textfont_10, Element.ALIGN_LEFT)); table.addCell(PdfFUtil.createCell(user.getRemarks(), textfont_10, Element.ALIGN_LEFT)); table.addCell(PdfFUtil.createCell(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                                .format(user.getCreateTime()), textfont_10, Element.ALIGN_LEFT)); } document.add(table);
//表格數據 /* 引入底部 */ footer(document,sdf); PdfFUtil.onEndPage(writer,document); //當前頁碼 } } else { System.out.println("沒有數據!!!"); // 此處根據自己的業務調整 } } /************************** 業務封裝 start ******************************/ /* 表格頭部公共的一行 */ public PdfPTable tbPublic(){ PdfPTable table_new = PdfFUtil.createTable(new float[] { 75, 110, 75, 140 }); table_new.addCell(PdfFUtil.createCell("審批節點", headfontnormal_12)); table_new.addCell(PdfFUtil.createCell("審批人", headfontnormal_12)); table_new.addCell(PdfFUtil.createCell("審批意見", headfontnormal_12)); table_new.addCell(PdfFUtil.createCell("審批時間", headfontnormal_12)); return table_new; } /* 底部公共部分 */ public void footer(Document document, String sdf) throws DocumentException { //表格下的落款——xxxxxx、打印時間 PdfPTable table_3 = PdfFUtil.createTable(new float[] { 75, 325}); table_3.addCell(PdfFUtil.createCell("xxxxxx", textfont_10, Element.ALIGN_LEFT, 1, false)); table_3.addCell(PdfFUtil.createCell("打印時間: "+sdf, textfont_10, Element.ALIGN_RIGHT, 1, false)); document.add(table_3); //表格下面的落款 } /* 公共頭部 */ public void header(Document document,PdfWriter writer) throws DocumentException, IOException { //todo logo圖片 Image image1 = Image.getInstance("D:/pdf/logo.png"); image1.setAlignment(Image.ALIGN_LEFT); image1.scalePercent(85); //依照比例縮放 //todo 條形碼 PdfContentByte cd = writer.getDirectContent(); Barcode128 code128 = new Barcode128(); code128.setCodeType(code128.CODE128); code128.setCode("12312312312"); code128.setBarHeight(28); code128.setFont(null); //設置為空,條形碼下方的數字就沒有了 Image image2 = code128.createImageWithBarcode(cd,null,null); image2.setAlignment(Image.ALIGN_RIGHT); image2.scalePercent(90); //依照比例縮放 image2.setAbsolutePosition(435,340);// x、y軸坐標 //todo 標題 Paragraph paragraph = new Paragraph("xxxxx", titlefontnormal_16); paragraph.setAlignment(1); //設置文字居中 0靠左 1,居中 2,靠右 paragraph.setIndentationLeft(12); //設置左縮進 paragraph.setIndentationRight(12); //設置右縮進 paragraph.setFirstLineIndent(24); //設置首行縮進 paragraph.setLeading(20f); //行間距 paragraph.setSpacingBefore(5f); //設置段落上空白 paragraph.setSpacingAfter(10f); //設置段落下空白 //todo 第一、二行 PdfPTable table_0 = PdfFUtil.createTable(new float[] { 75, 110, 75, 140 }); table_0.addCell(PdfFUtil.createCell("xxxxxx:", textfont_10, Element.ALIGN_CENTER, 1, false)); table_0.addCell(PdfFUtil.createCell("xxxxxx", underlinefont_10, Element.ALIGN_LEFT, 1, false)); table_0.addCell(PdfFUtil.createCell("xxxxxx:", textfont_10, Element.ALIGN_CENTER, 1, false)); table_0.addCell(PdfFUtil.createCell("xxxxxx", underlinefont_10, Element.ALIGN_LEFT, 1, false)); PdfPTable table_1 = PdfFUtil.createTable(new float[] { 75, 110, 75, 140 }); table_1.addCell(PdfFUtil.createCell("xxxxxx: ", textfont_10, Element.ALIGN_CENTER, 1, false)); table_1.addCell(PdfFUtil.createCell("xxxxxx", underlinefont_10, Element.ALIGN_LEFT, 1, false)); table_1.addCell(PdfFUtil.createCell("", textfont_10, Element.ALIGN_CENTER, 1, false)); table_1.addCell(PdfFUtil.createCell("", textfont_10, Element.ALIGN_LEFT, 1, false)); document.add(image1); // logo document.add(image2); // 條形碼 document.add(paragraph); // 標題 document.add(table_0); // 顯示第一行 document.add(table_1); // 顯示第二行 } /************************** 業務封裝 end ******************************/ /************************** 全局變量 start ******************************/ // 定義全局的字體靜態變量 private static Font titlefont_16; private static Font titlefontnormal_16; private static Font headfont_14; private static Font headfontnormal_14; private static Font headfont_12; private static Font headfontnormal_12; private static Font keyfont_10; private static Font textfont_10; private static Font underlinefont_10; // 靜態代碼塊 static { try { // 不同字體(這里定義為同一種字體:包含不同字號、不同style) BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); titlefont_16 = new Font(bfChinese, 16, Font.BOLD); headfont_14 = new Font(bfChinese, 14, Font.BOLD); headfont_12 = new Font(bfChinese, 12, Font.BOLD); keyfont_10 = new Font(bfChinese, 10, Font.BOLD); titlefontnormal_16 = new Font(bfChinese, 16, Font.NORMAL); headfontnormal_14 = new Font(bfChinese, 14, Font.NORMAL); headfontnormal_12 = new Font(bfChinese, 12, Font.NORMAL); textfont_10 = new Font(bfChinese, 10, Font.NORMAL); underlinefont_10 = new Font(bfChinese, 10, Font.UNDERLINE); } catch (Exception e) { e.printStackTrace(); } } /************************** 全局變量 end ******************************/ }

水印工具類:Watermark

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
/**
 * 水印工具類,調用此類即可,
 * 例如:writer.setPageEvent(new Watermark("XXXX"));// 水印
 */
public class Watermark extends PdfPageEventHelper {
    Font FONT = new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, new GrayColor(0.95f));
    private String waterCont;//水印內容
    public Watermark() {

    }
    public Watermark(String waterCont) {
        this.waterCont = waterCont;
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        for(int i=0 ; i<5; i++) {
            for(int j=0; j<5; j++) {
                ColumnText.showTextAligned(writer.getDirectContentUnder(),
                        Element.ALIGN_CENTER,
                        new Phrase(this.waterCont == null ? "HELLO WORLD" : this.waterCont, FONT),
                        (50.5f+i*350),
                        (40.0f+j*150),
                        writer.getPageNumber() % 2 == 1 ? 45 : -45);
            }
        }
    }
}

List分批處理例子:

List<Integer> dataList = new ArrayList<>();
        for (int i = 1; i <= 28; i++) {
            dataList.add(i);
        }

        //分批處理
        if (null != dataList && dataList.size() > 0) {
            int pointsDataLimit = 9;//限制條數(每頁顯示條數)
            Integer size = dataList.size();
            //判斷是否有必要分批
            if (pointsDataLimit < size) {
                int part = size / pointsDataLimit;//分批數(分幾頁)
                System.out.println("共有 : " + size + "條," + " 分為 :" + part + "批");
                int j = 0;
                for (int i = 1; i <= part; i++) {
                    System.out.println("第"+ i +"頁,這是頭部固定的");
                    List<Integer> listPage = dataList.subList(0, pointsDataLimit);
                    System.out.println(listPage);
                    //剔除
                    dataList.subList(0, pointsDataLimit).clear();
                    System.out.println("第"+ i +"頁,這是底部固定的");
                    j++;
                }

                if (!dataList.isEmpty()) {
                    List<Integer> listPage = dataList.subList(0, dataList.size());
                    System.out.println("第"+ (j+1) +"頁,這是頭部固定的");
                    System.out.println(listPage);
                    System.out.println("第"+ (j+1) +"頁,這是底部固定的");
                }
            } else {
                System.out.println(dataList);
            }
        } else {
            System.out.println("沒有數據!!!");
        }

 


免責聲明!

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



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