java通过Itext导出pdf

java通过Itext导出pdf


需要的POM文件

		<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.11</version>
        </dependency>

代码

/**
     * 设置字体
     *
     * @param fontsize
     * @param color
     * @param isBold
     * @return
     */
    public static Font setFont(Float fontsize, BaseColor color, Boolean isBold) {
        Font font = new Font();
        try {
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            font = new Font(baseFont, fontsize, isBold ? Font.BOLD : Font.NORMAL, color);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return font;
    }

    public static Font setFont(Float fontsize) {
        Font font = new Font();
        try {
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            font = new Font(baseFont, fontsize,Font.NORMAL, BaseColor.BLACK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return font;
    }

    public static Font setFont(Float fontsize, Boolean isBold) {
        Font font = new Font();
        try {
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            font = new Font(baseFont, fontsize, isBold ? Font.BOLD : Font.NORMAL, BaseColor.BLACK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return font;
    }
    private static BaseFont baseFont;
    private static Font font10;
    private static Font font10Bold;
    private static Font font11;
    private static Font font11Bold;
    private static Font font12;
    private static Font font12Bold;
    private static Font font14Bold;
    private static Font font16Bold;
    static {
        try {
            //使用iTextAsian.jar中的字体、并设置编码
            baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            font10 = PdfUtils.setFont(10f);
            font10Bold = PdfUtils.setFont(10f,true);
            font11 = PdfUtils.setFont(11f);
            font11Bold = PdfUtils.setFont(11f,true);
            font12 = PdfUtils.setFont(12f);
            font12Bold = PdfUtils.setFont(12f,true);
            font14Bold = PdfUtils.setFont(14f,true);
            font16Bold = PdfUtils.setFont(16f,true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public void courseRankInfoToPdf(Long courseId) {

        //---初始化数据
        CourseBaseScoreInfoBO baseScoreInfo = customVrTrainScoreMapper.getBaseScoreInfo(courseId);//获取课程基本信息
        String courseName = baseScoreInfo.getCourseName();//课程名称
        Integer totalPerson = baseScoreInfo.getTotalPerson();//参与人数
        if(totalPerson == 0){//当参与人数为0,说明该课程暂无成绩,不进行导出
            throw new CustomException("该课程暂无成绩,不支持导出");
        }
        String pdfName = courseName + "-成绩排名";
        float[] widths = {10, 15, 15, 15, 15, 15, 15};//百分比
        CourseRankInfoPdfModel scorePdfModel = new CourseRankInfoPdfModel();
        scorePdfModel.setCourseBaseScoreInfoBO(baseScoreInfo);
        scorePdfModel.setColumn(7);
        scorePdfModel.setWidths(widths);
        String title2 = "总分: "+baseScoreInfo.getTotalScore()+"  参与人数: "+totalPerson+"人";
        scorePdfModel.setTitle2(title2);
        scorePdfModel.setTitleSuffix("成绩排名");
        List<CourseScoreRankInfoBO> rankInfo = customVrTrainScoreMapper.getRankInfo(courseId);
        scorePdfModel.setCourseScoreRankInfoBOList(rankInfo);

        Document document = new Document(PageSize.A4);
        setPdfCommon(pdfName,document);
        try {
            addCourseRankInfoInfos(document,scorePdfModel);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        document.close();
    }
   
    void setPdfCommon(String pdfName,Document document){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(pdfName.getBytes(), "ISO-8859-1") + ".pdf");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            ServletOutputStream os = response.getOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, os);
            writer.setPageEvent(new HeaderFooter());// 页眉/页脚
            //writer.setPageEvent(new Watermark("捷安高科"));//水印,所有页面
            document.open();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }
 /**
     * 添加课程排名信息
     *
     * @param document
     * @throws DocumentException
     */
    private  void addCourseRankInfoInfos(Document document, CourseRankInfoPdfModel scorePdfModel) throws DocumentException {

        CourseBaseScoreInfoBO courseBaseScoreInfoBO = scorePdfModel.getCourseBaseScoreInfoBO();
        float[] widths = scorePdfModel.getWidths();
        String titleSuffix = scorePdfModel.getTitleSuffix();//标题后缀
        String courseName = courseBaseScoreInfoBO.getCourseName();//课程名称
        String title2S = scorePdfModel.getTitle2();//小标题

        //空行
        Paragraph blankLine = new Paragraph("\n", font12);
        document.add(blankLine);

        PdfPTable table = new PdfPTable(scorePdfModel.getColumn());

        addDocumentBaseInfos(table,widths,titleSuffix,courseName,title2S);

        setCell(table, "课程及格率", 2, font10Bold, true);//第二行第一列
        setCell(table, "任务总数", 1, font10Bold, true);//第二行第二列
        setCell(table, "平均分", 1, font10Bold, true);//第二行第三列
        setCell(table, "最高分", 1, font10Bold, true);//第二行第四列
        setCell(table, "最低分", 1, font10Bold, true);//第二行第五列
        setCell(table, "平均操作时长", 1, font10Bold, true);//第二行第六列

        setCell(table, courseBaseScoreInfoBO.getPassRate() + "%", 2, font14Bold);
        setCell(table, courseBaseScoreInfoBO.getTaskNum() + "个", 1, font11);
        setCell(table, courseBaseScoreInfoBO.getAvgScore() + "分", 1, font11);
        setCell(table, courseBaseScoreInfoBO.getMaxScore() + "分", 1, font11);
        setCell(table, courseBaseScoreInfoBO.getMinScore() + "分", 1, font11);
        String avgSeconds = courseBaseScoreInfoBO.getAvgSeconds();
        if(avgSeconds != null && avgSeconds.indexOf(".")>0){//操作时长单位是秒,保留两位小数,转换int需要截取后面小数
            avgSeconds = avgSeconds.substring(0,avgSeconds.indexOf("."));
        }else{
            avgSeconds = "0";
        }

        setCell(table, DateUtil.secondToTime(Integer.parseInt(avgSeconds)), 1, font11);


        setCell(table, "成绩排名", 7, font11Bold);

        setCell(table, "排名", 1, font10Bold, true);
        setCell(table, "账号", 2, font10Bold, true);
        setCell(table, "姓名", 1, font10Bold, true);
        setCell(table, "最高分", 1, font10Bold, true);
        setCell(table, "累计实训次数", 1, font10Bold, true);
        setCell(table, "累计实训时长", 1, font10Bold, true);

        List<CourseScoreRankInfoBO> courseScoreRankInfoBOList = scorePdfModel.getCourseScoreRankInfoBOList();

        for (CourseScoreRankInfoBO courseScoreRankInfoBO : courseScoreRankInfoBOList) {

            setCell(table, courseScoreRankInfoBO.getRankNo() + "", 1, font10);
            setCell(table, courseScoreRankInfoBO.getUserName(), 2, font10);
            setCell(table, courseScoreRankInfoBO.getRealName(), 1, font10);
            setCell(table, courseScoreRankInfoBO.getHighestScore() + "", 1, font10);
            setCell(table, courseScoreRankInfoBO.getTrainNum() + "", 1, font10);
            setCell(table, DateUtil.secondToTime(courseScoreRankInfoBO.getTotalSeconds()), 1, font10);
        }

        document.add(table);
    }

实体类代码

@Data
@ApiModel
public class CourseBaseScoreInfoBO {


    /**
     * 课程名称
     */
    @ApiModelProperty(value = "课程名称")
    private String courseName;

    /**
     * 总分
     */
    @ApiModelProperty(value = "总分")
    private Double totalScore;


    /**
     * 参与人数
     */
    @ApiModelProperty(value = "参与人数")
    private Integer totalPerson;

    /**
     * 及格率
     */
    @ApiModelProperty(value = "及格率")
    private Double passRate;

    /**
     * 任务总数
     */
    @ApiModelProperty(value = "任务总数")
    private Integer taskNum;

    /**
     * 平均分
     */
    @ApiModelProperty(value = "平均分")
    private Double avgScore;

    /**
     * 最高分
     */
    @ApiModelProperty(value = "最高分")
    private Double maxScore;

    /**
     * 最低分
     */
    @ApiModelProperty(value = "最低分")
    private Double minScore;


    /**
     * 平均操作时长
     */
    @ApiModelProperty(value = "平均操作时长")
    private String avgSeconds;

}

@Data
@ApiModel
public class CourseScoreRankInfoBO {


    /**
     * 排名
     */
    @ApiModelProperty(value = "排名")
    private Long rankNo;

    /**
     * 课程id
     */
    @ApiModelProperty(value = "用户id")
    private Long userId;


    /**
     * 账号
     */
    @ApiModelProperty(value = "账号")
    private String userName;


    /**
     * 总分
     */
    @ApiModelProperty(value = "姓名")
    private String realName;


    /**
     * 最高分
     */
    @ApiModelProperty(value = "最高分")
    private Double highestScore;

    /**
     * 累计实训次数
     */
    @ApiModelProperty(value = "累计实训次数")
    private Integer trainNum;

    /**
     * 累计实训时长
     */
    @ApiModelProperty(value = "累计实训时长")
    private Integer totalSeconds;




}
@Data
public class CourseRankInfoPdfModel {

    int column;//表格列数

    String titleSuffix;//表名后缀

    float[] widths;//表格列百分比

    String title2;//表格小标题

    CourseBaseScoreInfoBO courseBaseScoreInfoBO;//课程排名基本信息

    List<CourseScoreRankInfoBO> courseScoreRankInfoBOList;//课程排名信息数据

}

设置页眉页脚

public class HeaderFooter extends PdfPageEventHelper{
    // 总页数
    PdfTemplate totalPage;
    Font font11= PdfUtils.setFont(11f, BaseColor.BLACK, false);
    // 打开文档时,创建一个总页数的模版
    public void onOpenDocument(PdfWriter writer, Document document) {
        PdfContentByte cb =writer.getDirectContent();
        totalPage = cb.createTemplate(30, 16);
    }
    // 一页加载完成触发,写入页眉和页脚
    public void onEndPage(PdfWriter writer, Document document) {
        PdfPTable table = new PdfPTable(1);
        try {
            table.setTotalWidth(PageSize.A4.getWidth() - 80);
            table.setWidths(new int[] { 24});
            table.setLockedWidth(true);
            table.getDefaultCell().setFixedHeight(-10);
            table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);

            table.addCell(new Paragraph("导出时间: "+ DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS_), font11));// 可以直接使用addCell(str),不过不能指定字体,中文无法显示

            // 将页眉写到document中,位置可以指定,指定到下面就是页脚
            table.writeSelectedRows(0, -1, 70, PageSize.A4.getHeight() - 20, writer.getDirectContent());
        } catch (Exception de) {
            throw new ExceptionConverter(de);
        }
        PdfPTable table2 = new PdfPTable(1);
        try {
            table2.setTotalWidth(PageSize.A4.getWidth() - 80);
            table2.setWidths(new int[] { 24});
            table2.setLockedWidth(true);
            table2.getDefaultCell().setFixedHeight(-10);
            table2.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            table2.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(new Paragraph("第 " + writer.getPageNumber() + " 页", font11));

            // 将页眉写到document中,位置可以指定,指定到下面就是页脚
            table2.writeSelectedRows(0, -1, 40, 40, writer.getDirectContent());
        } catch (Exception de) {
            throw new ExceptionConverter(de);
        }
    }

}

导出效果图

在这里插入图片描述
参考文章:Itext设置页眉页脚、表头划线、水印、条形码、二维码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值