SpringCloud下载PDF.The document has no pages

版权声明:本文为博主原创文章,欢迎转载,转载请注明作者、原文超链接 ,博主地址:https://blog.csdn.net/qq_31122833。 https://blog.csdn.net/qq_31122833/article/details/81982492

1、首先导入两个依赖

<!-- itext方式导出pdf -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>4.2.2</version>
        </dependency>
<!-- 打印中文 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

2、Controller核心代码:

/**
     * 下载--班级pdf文档
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/downloadClass")
    public void downloadClass(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/pdf");
        //下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=user.pdf");
        //设置中文
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);

        Document document = new Document();
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        document.addTitle("班级数据");
        document.addAuthor("鲁达");
        document.addCreationDate();
        document.addKeywords("123");
        document.addLanguage("中文");
        //表头
        PdfPTable title = new PdfPTable(3);
        title.addCell(new Paragraph("班级id",FontChinese));
        title.addCell(new Paragraph("专业id",FontChinese));
        title.addCell(new Paragraph("班级名称",FontChinese));
        document.add(title);
        List<TblClass> tblClassList = tblClassService.getTblClassListData(null).getData();
        for (TblClass tblClass : tblClassList) {
            //插入数据
            PdfPTable table = new PdfPTable(3);
            table.addCell(new Paragraph(tblClass.getId().toString(),FontChinese));
            table.addCell(new Paragraph(tblClass.getProfessionId().toString(),FontChinese));
            table.addCell(new Paragraph(tblClass.getName().toString(),FontChinese));
            document.add(table);
        }
        document.close();
    }

如果报错:The document has no pages。也就是在document.close()报错时,看看表头设置的列数和addCell的数量是否一致,否则将会报错:The document has no pages。如下,我设置3列,addCell三个数据

//表头
        PdfPTable title = new PdfPTable(3);
        title.addCell(new Paragraph("班级id",FontChinese));
        title.addCell(new Paragraph("专业id",FontChinese));
        title.addCell(new Paragraph("班级名称",FontChinese));

猜你喜欢

转载自blog.csdn.net/qq_31122833/article/details/81982492