itext生成pdf文件 设置pdf单元格背景颜色 隔行换色

SpringBoot项目生成PDF格式文件

1、引入jar

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.12</version>
</dependency>
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.8</version>
</dependency>
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox-tools</artifactId>
    <version>2.0.8</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
    <scope>compile</scope>
</dependency>

代码示例:
/**
     *  数据填充
     * @param fileName 下载文件名称
     * @param dataMap 填充文件正文数据集
     * @param headMap 填充文件头数据集
     */
    public static void unitAllCensusReport(String fileName, List<Map<String, Object>> dataMap, Map<String, Object> headMap,Integer itemType) {
        try{
    //创建PDF文件,设置基础参数
            Document doc = setPdfBasic(fileName);
            String docTitle = "单位终端检查统计报告";//文件标题
            doc.open();
        //文件头信息
            headDesc(doc, docTitle, headMap);//检查单位(fromOrgName)、任务名称(taskName)、检查日期(executeDate)
            int colNum = 12;
        //pdf文件内容中表格表头设置
            String[] headText = new String[]{"序号","单位","受检计算机总数","未完成计算机总数","违规计算机总数","违规计算机比例","违规记录数","关键词命中文件数","XX标志文件数","XX文件数","已判定文件数","违规文件数"};
            PdfPTable tableBody = generateTable(headText,dataMap,colNum,itemType);
            doc.add(tableBody);
            doc.add(getBlankRow(50f));

            userAndUnitSign(doc);//检查人员(签字)、检查单位人员(签字)、日期

            doc.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 设置输出文档基础信息
     * @param fileName
     * @return
     */
    public static Document setPdfBasic(String fileName){
        FileOutputStream out;//文档输出保存路径
        try {
            out = new FileOutputStream(fileName);
            Rectangle rectangle = new Rectangle(PageSize.A4);//页面大小(画出矩形轮廓)
            rectangle.setBackgroundColor(BaseColor.WHITE);//页面背景颜色
            Document doc = new Document(rectangle);
            PdfWriter writer = PdfWriter.getInstance(doc,out);
            writer.setPdfVersion(PdfWriter.VERSION_1_2);
            doc.setMargins(20,20,30,30);//页边空白
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

        //检查单位、检查任务、检查时间
    private static void headDesc(Document doc, String docTitle, Map<String,Object> headMap) throws DocumentException, IOException {
        //首个段落信息设置
    Paragraph paragraph = new Paragraph(docTitle, setNormalFont(11,Font.BOLD));
        paragraph.setAlignment(Element.ALIGN_CENTER);//对齐方式
        doc.add(paragraph);
        doc.add(getBlankRow(30f));

        //检查单位(fromOrgName)、任务名称(taskName)、检查日期(executeDate)
        String checkUnit = Func.isEmpty(headMap.get("fromOrgName")) ? "                                 " : headMap.get("fromOrgName").toString();//检查单位
        String taskName = Func.isEmpty(headMap.get("taskName")) ? "                                 " : headMap.get("taskName").toString();//检查任务
        String checkDate = Func.isEmpty(headMap.get("executeDate")) ? DateUtils.formatDate(new Date(),"yyyy年MM月dd日") :
                headMap.get("executeDate").toString().substring(0,11);//检查日期
        String title="                检查单位:"+checkUnit+"                检查任务:"+taskName+"               检查日期:"+checkDate;
    //设置新的段落内容
        Paragraph subTitle = new Paragraph(title, setNormalFont(11,Font.NORMAL));//设置字号大小和样式
        subTitle.setIndentationLeft(20);//左缩进
        doc.add(subTitle);
        doc.add(getBlankRow(10f));
    }

   /**
     * @return 生产pdf文件中table
     * @throws DocumentException 异常
     * @throws IOException 异常
     */
    private static PdfPTable generateTable(String [] headText, List<Map<String, Object>> list, int colNum) throws DocumentException,IOException {
        // 创建一个只有n列的表格
        PdfPTable table = new PdfPTable(colNum);
        table.setTotalWidth(500);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.getDefaultCell().setBorder(1);
        Font textFont = setNormalFont(11,Font.NORMAL);//设置字号大小和样式

        //设置表头
        for(int i = 0 ; i < colNum ; i++){
    //添加列表表头有背景色单元格(单元格内容居中)
            table.addCell(contCenterBgCell(headText[i], textFont, 1));
        }
        int checkNumTotal=0,incompleteTotal=0,foulTotal=0,violationTotal=0,keyWordHitTotal=0,levelMarkTotal=0,
                encryptionTotal =0,determinedTotal=0,violationFileTotal=0,violationRateTotal=0;
        for (int i = 0 ; i < list.size();i++){
            // 列表数据集合
            Map<String,Object> rowData = list.get(i);
            if(rowData != null){
        //添加内容居左展示的单元格
                table.addCell(contLeftCell(i+1+"",textFont,1));//序号
        //创建内容默认居中的单元格
                table.addCell(createCell(rowData.get("orgName").toString(),textFont,1));
                checkNumTotal+= Integer.valueOf(rowData.get("checkNum").toString());
                incompleteTotal += Integer.valueOf(rowData.get("incomplete").toString());
                foulTotal += Integer.valueOf(rowData.get("foul").toString());
                violationTotal += Integer.valueOf(rowData.get("violation").toString());
                keyWordHitTotal += Integer.valueOf(rowData.get("keyWordHit").toString());
                levelMarkTotal += Integer.valueOf(rowData.get("levelMark").toString());
                encryptionTotal += Integer.valueOf(rowData.get("encryption").toString());
                determinedTotal += Integer.valueOf(rowData.get("determined").toString());
                violationFileTotal += Integer.valueOf(rowData.get("violationFile").toString());
                table.addCell(createCell(rowData.get("checkNum").toString(),textFont,1));
                table.addCell(createCell(rowData.get("incomplete").toString(),textFont,1));
                table.addCell(createCell(rowData.get("foul").toString(),textFont,1));
                table.addCell(createCell(rowData.get("violationRate")+"%",textFont,1));
                table.addCell(createCell(rowData.get("violation").toString(),textFont,1));
                table.addCell(createCell(rowData.get("keyWordHit").toString(),textFont,1));
                table.addCell(createCell(rowData.get("levelMark").toString(),textFont,1));
                table.addCell(createCell(rowData.get("encryption").toString(),textFont,1));
                table.addCell(createCell(rowData.get("determined").toString(),textFont,1));
                table.addCell(createCell(rowData.get("violationFile").toString(),textFont,1));
            }
        }
        table.addCell(createCell("合计",textFont,2));
        table.addCell(createCell(checkNumTotal+"",textFont,1));
        table.addCell(createCell(incompleteTotal+"",textFont,1));
        table.addCell(createCell(foulTotal+"",textFont,1));
        if(!Func.equals(foulTotal,0) && !Func.equals(checkNumTotal,0)){
            violationRateTotal = new BigDecimal(foulTotal).divide(new BigDecimal(checkNumTotal),2,BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100)).intValue();
        }
        table.addCell(createCell(violationRateTotal+"%",textFont,1));
        table.addCell(createCell(violationTotal+"",textFont,1));
        table.addCell(createCell(keyWordHitTotal+"",textFont,1));
        table.addCell(createCell(levelMarkTotal+"",textFont,1));
        table.addCell(createCell(encryptionTotal+"",textFont,1));
        table.addCell(createCell(determinedTotal+"",textFont,1));
        table.addCell(createCell(violationFileTotal+"",textFont,1));
    
        /*设置隔行换色*/
        PdfPTableEvent event = new AlterNatingBackgroud();
        table.setTableEvent(event);

        
        return table;
    }

    //生成默认空白行
    private static Paragraph getBlankRow(float leading) throws DocumentException, IOException {
        Paragraph blankRow = new Paragraph(" ", setNormalFont(14,Font.NORMAL));//设置字号大小和样式
        blankRow.setAlignment(Element.ALIGN_CENTER);
        blankRow.setLeading(leading);//行间距
        return blankRow;
    }

    /**
     * 为表格添加一个内容
     * @param value           值
     * @param font            字体
     * @return                添加的单元格
     */
    private 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           字体
     * @param colspan       占多少列
     * @return              添加的单元格
     */
    private static PdfPCell createCell(String value, Font font, int colspan){
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 为表格添加一个内容居左展示的单元格
     * @param value          值
     * @param font           字体
     * @param colspan       占多少列
     * @return              添加的单元格
     */
    private static PdfPCell contCenterBgCell(String value, Font font, int colspan){
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setColspan(colspan);
        cell.setBackgroundColor(new BaseColor(235,235,235));
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 为表格添加一个内容居左展示的单元格
     * @param value          值
     * @param font           字体
     * @param colspan       占多少列
     * @return              添加的单元格
     */
    private static PdfPCell contLeftCell(String value, Font font, int colspan){
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_LEFT);
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    //设置字体、字体颜色、大小等
    private static Font setNormalFont(int fontSize,int fontStyle) throws DocumentException,IOException{
        simpleChines = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);//设置文本字体
        chineseFont = new Font(simpleChines,fontSize,fontStyle,BaseColor.BLACK);//设置文本字号及颜色
        return chineseFont;
    }

添加PDF隔行换色事件,java类:


import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPTableEvent;

/**
 * 添加PdfPtable背景颜色
 */
public class AlterNatingBackgroud implements PdfPTableEvent {

    @Override
    public void tableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
        int columns;
        Rectangle rect;
        //合适的颜色:(235,235,235)
        int footer = widths.length - table.getFooterRows();
        int header = table.getHeaderRows() - table.getFooterRows() + 1;
        for(int row = header;row <footer;row+=2){
            columns = widths[row].length -1;
            rect = new Rectangle(widths[row][0],heights[row],widths[row][columns],heights[row + 1]);
            rect.setBackgroundColor(new BaseColor(235,235,235));
            rect.setBorder(Rectangle.NO_BORDER);
            canvases[PdfPTable.BASECANVAS].rectangle(rect);
        }
    }

}

多数内容百度而来,拼装为自己想要的效果~~~如有违权,请通知处理!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值