栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

SpringBoot项目生成PDF格式文件

1、引入jar


    com.itextpdf
    itextpdf
    5.5.12


    org.apache.pdfbox
    pdfbox
    2.0.8


    org.apache.pdfbox
    pdfbox-tools
    2.0.8


    com.itextpdf
    itext-asian
    5.2.0


    com.itextpdf
    itextpdf
    5.5.13
    compile

代码示例:

    public static void unitAllCensusReport(String fileName, List> dataMap, Map 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();
        }
    }

   
    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 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));
    }

   
    private static PdfPTable generateTable(String [] headText, List> 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 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;
    }

   
    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;
    }


   
    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;
    }

   
    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;
    }

   
    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;


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
            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);
        }
    }

}

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/975837.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号