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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章