Spring導出PDF

Spring導出PDF
代碼如下:

package cn.xaele.qx.kq.ctrl;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Element;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.Phrase;

import cn.xaele.qx.kq.bean.QxOpLog;
import cn.xaele.utils.pdf.AbstractIText5PdfView;
import cn.xaele.utils.pdf.PdfRotateEvent;
import cn.xaele.utils.pdf.PdfUtils;

public class QxOpLog_PdfView extends AbstractIText5PdfView {
    // 日誌輸出
    private static final Logger log = LogManager.getLogger(QxOpLog_ExcelView.class);
    // 測試標記
    private boolean isTest = false;
    // 設置輸出列表題頭內容
    private String[] fieldName = { "序號", "操作員", "權限名稱", "ip地址", "操作信息", "操作時間" };
    // 設置列表頭寬度
    private float tableContentWidth[] = { 4.3f, 11f, 18f, 12.5f, 60.5f, 12.0f};

    /**
     * 設置打印頁面紙張大小
     */
    @Override
    protected Document createPdfDocument() throws Exception {
        Document document = new Document(PdfUtils.getRectangle_A4_H(), -20, -20, 20, 20);
        return document;
    }

    /**
     * 構建PDF
     */
    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        @SuppressWarnings("unchecked")
        List<QxOpLog> objList = (List<QxOpLog>) model.get("objList");
        if (objList == null) {
            objList = new ArrayList<>();
        }
        if (isTest) {
            log.info("objList-------------->" + objList.toString());
        }

        BaseFont bfZH = PdfUtils.getBaseFont();
        Font cellFont = new Font(bfZH, 9, Font.NORMAL);

        // 每頁最多18行
        int itemPerPage = 18;
        // 計算總頁數
        int totalPageNum = (objList.size() - 1) / itemPerPage + 1;

        for (int page = 0; page < totalPageNum; page++) {
            int startIdx = page * itemPerPage;
            int endIdx = (page + 1) * itemPerPage;
            if (endIdx > objList.size()) {
                endIdx = objList.size();
            }
            Chapter chapter1 = new Chapter("", page);
            chapter1.setNumberDepth(0);

            int tableRowHeight = 28;

            // 打印標題
            PdfPTable subTitleTable = createSubTitleTable("操作日誌", bfZH);
            chapter1.add(subTitleTable);

            PdfPTable pdfContentTable = new PdfPTable(fieldName.length);
            try {
                pdfContentTable.setWidths(tableContentWidth);
            } catch (DocumentException e) {
                e.printStackTrace();
            }

                // 按照分頁條件獲取記錄
                for (int num = startIdx; num < endIdx; num++) {
                    QxOpLog bean = objList.get(num);
                    PdfPCell cell = PdfUtils.getPdfPCell(num + 1, cellFont, Element.ALIGN_CENTER, tableRowHeight);
                    cell.setBorderWidth(1);
                    pdfContentTable.addCell(cell);

                    cell = PdfUtils.getPdfPCell(bean.getOpName(), cellFont, Element.ALIGN_CENTER, tableRowHeight);
                    cell.setBorderWidth(1);
                    pdfContentTable.addCell(cell);

                    cell = PdfUtils.getPdfPCell(bean.getPurviewName(), cellFont, Element.ALIGN_CENTER, tableRowHeight);
                    cell.setBorderWidth(1);
                    pdfContentTable.addCell(cell);

                    cell = PdfUtils.getPdfPCell(bean.getOpIp(), cellFont, Element.ALIGN_CENTER, tableRowHeight);
                    cell.setBorderWidth(1);
                    pdfContentTable.addCell(cell);

                    cell = PdfUtils.getPdfPCell(bean.getOpInfo(), cellFont, Element.ALIGN_CENTER, tableRowHeight);
                    cell.setBorderWidth(1);
                    pdfContentTable.addCell(cell);

                    cell = PdfUtils.getPdfPCell(bean.getOpTimeStr(), cellFont, Element.ALIGN_CENTER, tableRowHeight);
                    cell.setBorderWidth(1);
                    pdfContentTable.addCell(cell);
                }
            // 保存到頁面中
            chapter1.add(pdfContentTable);

            document.add(chapter1);
        }

    }

    public PdfPTable createSubTitleTable(String title, BaseFont bfZH) {
        Font subTitleFont = new Font(bfZH, 12, Font.NORMAL);
        // 設置各列寬度,單位是百分比
        int width1[] = { 20, 60, 20 };
        PdfPTable table = new PdfPTable(3);
        try {
            table.setWidths(width1);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        PdfPCell cell = new PdfPCell(new Phrase("", subTitleFont));
        // cell.setBorderColor(BaseColor.WHITE);
        cell.setBorderWidth(0);
        cell.setPadding(8);
        cell.setFixedHeight(32);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase(title, subTitleFont));
        // cell.setBorderColor(BaseColor.WHITE);
        cell.setBorderWidth(0);
        cell.setPadding(8);
        cell.setFixedHeight(32);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("", subTitleFont));
        // cell.setBorderColor(BaseColor.WHITE);
        cell.setBorderWidth(0);
        cell.setPadding(8);
        cell.setFixedHeight(32);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        table.addCell(cell);

        return table;
    }
}

對PDF的一些簡單封裝

package cn.xaele.utils.pdf;

import java.io.IOException;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;

import cn.xaele.utils.StringUtils;

public class PdfUtils {

    public static void main(String[] args) {
        // 默認爲72px的大小。查看源碼可發現PageSize.A4 = new Rectangle(595.0F, 842.0F);//像素
        // 默認的度量系統以排版單位磅爲基礎得出其它單位的近似值,如1英寸=72磅
        // 如想在A4頁面的PDF中創建一個矩形,需要計算以下數據:
        // 21釐米 / 2.54 = 8.2677英寸
        // 8.2677英寸 * 72 = 595磅
        // 29.7釐米 / 2.54 = 11.6929英寸
        // 11.6929英寸 * 72 = 842磅
        // 默認邊距爲36磅即半英寸
        //
        //
    }

    /**
     * 獲取平臺無關回車符
     * 
     * @return String 平臺無關回車符
     */
    public static String getReturn() {
        return System.getProperty("line.separator");
    }

    /**
     * A3紙張,縱向托盤走紙,縱向打印
     * 
     * @return
     */
    public static Rectangle getRectangle_A3_V() {
        Rectangle pageSize = new Rectangle(PageSize.A3);
        return pageSize;
    }

    /**
     * A3紙張,橫向托盤走紙,橫向打印
     * 
     * @return
     */
    public static Rectangle getRectangle_A3_H() {
        Rectangle pageSize = new Rectangle(PageSize.A3).rotate();
        return pageSize;
    }

    /**
     * A4紙張,縱向托盤走紙,縱向打印
     * 
     * @return
     */
    public static Rectangle getRectangle_A4_V() {
        Rectangle pageSize = new Rectangle(PageSize.A4);
        return pageSize;
    }

    /**
     * A4紙張,橫向托盤走紙,橫向打印
     * 
     * @return
     */
    public static Rectangle getRectangle_A4_H() {
        Rectangle pageSize = new Rectangle(PageSize.A4).rotate();
        return pageSize;
    }

    /**
     * A4紙張,縱向托盤走紙,橫向打印(需要在系統中對打印內容進行旋轉)
     * 
     * @return
     */
    public static Rectangle getRectangle_A4_V1() {
        Rectangle pageSize = new Rectangle(PageSize.A4.getLeft(), PageSize.A4.getBottom(), PageSize.A4.getTop(),
                PageSize.A4.getRight());// 可正常旋轉90度
        return pageSize;
    }

    /**
     * 獲取基礎字符集
     * 
     * @return
     */
    public static BaseFont getBaseFont() {
        BaseFont bfZH = null;
        try {
            StringUtils utils = new StringUtils();
            bfZH = BaseFont.createFont(utils.GetTomcatFontsPath() + "/msyh.ttf", BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return bfZH;
    }

    /**
     * 獲取“仿宋”字體
     * 
     * @return
     */
    public static BaseFont getBaseFontFangSong() {
        BaseFont bfZH = null;
        try {
            StringUtils utils = new StringUtils();
            bfZH = BaseFont.createFont(utils.GetTomcatFontsPath() + "/simfang.ttf", BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return bfZH;
    }

    /**
     * 獲取“黑體”字體
     * 
     * @return
     */
    public static BaseFont getBaseFontHeiTi() {
        BaseFont bfZH = null;
        try {
            StringUtils utils = new StringUtils();
            bfZH = BaseFont.createFont(utils.GetTomcatFontsPath() + "/simhei.ttf", BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return bfZH;
    }

    /**
     * 獲取“楷體”字體
     * 
     * @return
     */
    public static BaseFont getBaseFontKaiTi() {
        BaseFont bfZH = null;
        try {
            StringUtils utils = new StringUtils();
            bfZH = BaseFont.createFont(utils.GetTomcatFontsPath() + "/simkai.ttf", BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return bfZH;
    }

    /**
     * 獲取“宋體”字體
     * 
     * @return
     */
    public static BaseFont getBaseFontSongTi() {
        BaseFont bfZH = null;
        try {
            StringUtils utils = new StringUtils();
            bfZH = BaseFont.createFont(utils.GetTomcatFontsPath() + "/simsun.ttc", BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return bfZH;
    }

    /**
     * 初始化PdfCell
     * 
     * @param cellValue
     * @param cellFont
     * @return
     */
    public static PdfPCell getPdfPCell(String cellValue, Font cellFont) {
        PdfPCell cell = new PdfPCell(new Phrase(cellValue, cellFont));
        cell.setFixedHeight(18);
        cell.setPadding(0);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        return cell;
    }

    /**
     * 初始化PdfCell
     * 
     * @param cellValue
     * @param cellFont
     * @param align
     * @return
     */
    public static PdfPCell getPdfPCell(String cellValue, Font cellFont, int align) {
        PdfPCell cell = new PdfPCell(new Phrase(cellValue, cellFont));
        cell.setFixedHeight(18);
        cell.setPadding(2);
        cell.setHorizontalAlignment(align);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        return cell;
    }

    /**
     * 初始化PdfCell
     * 
     * @param cellValue
     * @param cellFont
     * @param align
     * @param cellHeight
     * @return
     */
    public static PdfPCell getPdfPCell(String cellValue, Font cellFont, int align, int cellHeight) {
        PdfPCell cell = new PdfPCell(new Phrase(cellValue, cellFont));
        cell.setFixedHeight(cellHeight);
        cell.setPadding(0);
        cell.setHorizontalAlignment(align);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        return cell;
    }

    /**
     * 初始化PdfCell
     * 
     * @param cellValue
     * @param cellFont
     * @param align
     * @param cellHeight
     * @return
     */
    public static PdfPCell getPdfPCell(int cellValue, Font cellFont, int align, int cellHeight) {
        // 不顯示0值
        String val = cellValue == 0 ? "" : "" + cellValue;
        PdfPCell cell = new PdfPCell(new Phrase(val, cellFont));
        cell.setFixedHeight(cellHeight);
        cell.setPadding(0);
        cell.setHorizontalAlignment(align);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        return cell;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章