The page 1 was requested but the document has only 0 pages.

来源:互联网 发布:网络借贷百度百科 编辑:程序博客网 时间:2024/05/18 01:30

使用iText生成pdf文件的时候,遇到这个错误,上网找了好久都没有找到解决办法。把我们的解决办法放到这里,有借无勉。

先贴代码:

Document document = new Document(PageSize.A4,50,50,50,50);// 建立一个Document对象        try {            PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream(file));        } catch (Exception e) {            e.printStackTrace();            return null;        }        document.open();//打开写入流        Paragraph title=new Paragraph(departmentEntity.getName()+"学习记录报表——"+CalendarTool.formatYYYYMMdd(new Date()),titlefont );        title.setAlignment(Element.ALIGN_CENTER);        title.setSpacingAfter(20);        Chapter chapter=new Chapter(title,1);        chapter.setNumberDepth(0);        Section section=chapter.addSection(new Paragraph("单位人员学习记录",titlefont));        Paragraph tableDesc=new Paragraph("单位共有"+studyRecordList.size()+"人");        PdfPTable table=new PdfPTable(7);        table.setSpacingBefore(25);        table.setSpacingAfter(25);        int order=0;        //先创建表头        table.addCell(createCell("序号",keyfont));        table.addCell(createCell("用户编号",keyfont));        table.addCell(createCell("用户姓名",keyfont));        table.addCell(createCell("周学习次数",keyfont));        table.addCell(createCell("周完成率",keyfont));        table.addCell(createCell("月学习次数",keyfont));        table.addCell(createCell("月完成率",keyfont));        for (DepartmentUserStudyRecord studyRecord:studyRecordList){            order++;//增加序号            table.addCell(createCell(order+"",textfont));            table.addCell(createCell(studyRecord.getAdmId(),textfont));            table.addCell(createCell(studyRecord.getUserName(),textfont));            table.addCell(createCell(studyRecord.getWeeklyStudyNum()+"",textfont));            table.addCell(createCell(studyRecord.getWeeklyStudyRate()*100+"%",textfont));            table.addCell(createCell(studyRecord.getMonthlyStudyNum()+"",textfont));            table.addCell(createCell(studyRecord.getMonthlyStudyRate()*100+"%",textfont));        }        section.add(table);        Section section1=chapter.addSection(new Paragraph("单位学习完成率",titlefont));        Paragraph deptResult=new Paragraph("单位周完成率:"+DweeklyStudyRate*100+"%,月完成率:"+DmonthlyStudyRate*100+"%。",textfont);        deptResult.setSpacingBefore(20);        deptResult.setAlignment(Element.ALIGN_CENTER);        section1.add(deptResult);        try {            document.newPage();            document.add(chapter);        } catch (DocumentException e) {            e.printStackTrace();        }        document.close();//关闭写入流        return file;

在document.close()的这一步抛出了异常,保存为The page 1 was requested but the document has only 0 pages。而对应的pdf文件已经存在,文件大小为0字节。后来又把 document.add(chapter);删掉之后,报了document has no pages的错误。而在同学的电脑上,却可以成功执行。
比对两台电脑的环境,并没有什么大的区别。巧合的是,我又检查了一下iText的包:
由maven引入的包
除此之外:
还有一个itext-asian.jar包。
和同学的对比,发现iText-asian.jar包忘记引入了。所以就出现了上面的错。

如果可以帮到大家,很高兴。

阅读全文
0 0