Java操作PDF报表-iText的使用

iText组件

生成PDF报表的Java组件–iText,通过在服务器端生成PDF报表,客户端采用超链接显示或下载得到生成的报表。

iText组件的下载

maven坐标:

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

iText的基本使用

     public static void main(String[] args) {
        //下载pdf文档
        try {
            //1.创建文档
            Document document = new Document();
            //2.新建pdf实例
            PdfWriter.getInstance(document, new FileOutputStream(new File("f:/hello.pdf")));
            //3.打开文档
            document.open();
            //4.文档中写入内容
            document.add(new Paragraph("hello world"));
            //5.关闭文档
            document.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

iText的进阶使用

         /**
         * 导出分区pdf
         * @return
         * @throws Exception
         */
        @Action("subarea_exportPdf")
        public String exportPdf() throws Exception{
            //1.从数据库查询查询出来的数据列表
            //获取业务查询条件
            Specification<Subarea> specification = getSubareaSpecifiaction();
            //调用业务层查询数据
            List<Subarea> subareaList = subareaService.findSubareaList(specification);

            //放入响应下载
            String downFilename = "分区数据.pdf";
            //获取文件类型
            String mimeType = ServletActionContext.getServletContext().getMimeType(downFilename);
            //将文件类型放入响应
            ServletActionContext.getResponse().setContentType(mimeType);
            //设置浏览器类型
            String agent = ServletActionContext.getRequest().getHeader("user-agent");
            //解决附件名编码
            downFilename = FileUtils.encodeDownloadFilename(downFilename, agent);
            //获取附件名称和下载方式
            String contentDisposition = "attachment;filename="+downFilename;
            //将附件名称和下载方式放入响应头信息中  
            ServletActionContext.getResponse().setHeader("Content-Disposition", contentDisposition);

            //将文件流写入客户端响应中
            HttpServletResponse response = ServletActionContext.getResponse();

            //根据数据生成pdf

            try {
                //1.创建一个文档
                Rectangle rectangle = new Rectangle(PageSize.A4);
                //设置文档四周间距
                Document document = new Document(rectangle,40,40,40,40);
                //指定文档的输出位置
                PdfWriter.getInstance(document, response.getOutputStream());
                //3.打开文档
                document.open();
                //4.准备写入内容
                //参数1:使用宋体来写pdf文档
                //参数2:字体编码,gbk
                //参数3:是否内置字体:如果不内置:优点:文件个头小,缺点:打开文档的os中没有该字体,可能显示不正常
                //如果内置:优点:os不需要有该字体,也能正常显示,缺点:文件个头大
                BaseFont baseFontChinese = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, BaseFont.NOT_EMBEDDED);

                //文档标题
                //参数1:相当于字体(宋体)
                //参数2:字体大小
                //参数3:是否加粗,斜体
                //参数4:字体颜色
                Font headerFont = new Font(baseFontChinese,30,Font.BOLD,BaseColor.PINK);
                //构建一个段落
                Paragraph headerParagraph = new Paragraph("分区列表",headerFont);
                //文字居中
                headerParagraph.setAlignment(Paragraph.ALIGN_CENTER);
                //将添加到文档中
                document.add(headerParagraph);

                //文档副标题
                Font header2font = new Font(baseFontChinese,20,Font.ITALIC,BaseColor.CYAN);
                //构建一个段落
                Paragraph header2Paragraph = new Paragraph("张三",header2font);
                //文字居右
                header2Paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
                //设置行间距
                header2Paragraph.setLeading(29f);
                //将副标题加入到文档中
                document.add(header2Paragraph);

                //文档正文
                //设置表格头部字体
                Font tableHeaderFont = new Font(baseFontChinese,10,Font.BOLD,BaseColor.BLUE);
                //设置表格内容字体
                Font tablebodyFont = new Font(baseFontChinese,10,Font.NORMAL,BaseColor.BLACK);

                //构建一个表格
                PdfPTable pdfPTable = new PdfPTable(7);
                pdfPTable.setSpacingBefore(29f);//设置表格到上面段落的高度

                pdfPTable.setLockedWidth(true);
                //设置表格的宽度和高度
                pdfPTable.setTotalWidth(800);
                pdfPTable.setTotalWidth(new float[]{60,60,60,50,50,50,150});

                //水平对其方式
                pdfPTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //垂直对其方式
                pdfPTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);

                //Paragraph:段落,换行
                //Phrase:一段文字,不换行
                //设置表头内容
                pdfPTable.addCell(new PdfPCell(new Phrase("分区编号", tableHeaderFont)));
                pdfPTable.addCell(new PdfPCell(new Phrase("区域编码", tableHeaderFont)));
                pdfPTable.addCell(new PdfPCell(new Phrase("关键字", tableHeaderFont)));
                pdfPTable.addCell(new PdfPCell(new Phrase("起始号",tableHeaderFont)));
                pdfPTable.addCell(new PdfPCell(new Phrase("结束号",tableHeaderFont)));
                pdfPTable.addCell(new PdfPCell(new Phrase("单双号",tableHeaderFont)));
                pdfPTable.addCell(new PdfPCell(new Phrase("位置信息",tableHeaderFont)));

                //表格内容
                PdfPCell cell = new PdfPCell();
                cell.setPadding(5f);//设置padding

                for (Subarea subarea : subareaList) {
                    cell.setPhrase(new Phrase(subarea.getId(),tablebodyFont));
                    pdfPTable.addCell(cell);
                    cell.setPhrase(new Phrase(subarea.getRegion().getId(),tablebodyFont));
                    pdfPTable.addCell(cell);
                    cell.setPhrase(new Phrase(subarea.getAddresskey(),tablebodyFont));
                    pdfPTable.addCell(cell);
                    cell.setPhrase(new Phrase(subarea.getStartnum(),tablebodyFont));
                    pdfPTable.addCell(cell);
                    cell.setPhrase(new Phrase(subarea.getEndnum(),tablebodyFont));
                    pdfPTable.addCell(cell);
                    cell.setPhrase(new Phrase(subarea.getSingle().toString(),tablebodyFont));
                    pdfPTable.addCell(cell);
                    cell.setPhrase(new Phrase(subarea.getPosition(),tablebodyFont));
                    pdfPTable.addCell(cell);

                }

                //段落添加到文档中
                document.add(pdfPTable);
                //5.释放资源
                document.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("PDF文件下载失败!");
            }

            //响应的是文件流
            return NONE;
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用com.lowagie.text.pdf插件编写的PDF报表工具类,支持动态报表创建,使用简单,附件中包含了测试类和生成的报表文件。附件中的代码需要修改相关的保存路径后可以直接使用。创建一张报表例子: private JsFileExportResult createRowReport() { String condition = "开始时间:2018-02-02 14:00:30 结束时间:2018-02-06 16:00:30"; PDFGridReport pdfReport = new PDFGridReport("报表创建测试", GridReportTestModel.getModels()); pdfReport.addCondition(condition); pdfReport.header("字段名称1", "item1", 0, 0).width(160); pdfReport.header("字段名称3", "item3", 0, 2).getCell().backgroundColor(Color.ORANGE); pdfReport.header("字段名称4", "item4", 0, 3); pdfReport.header("字段名称5", "item5", 0, 4); pdfReport.header("字段名称2", "item2", 0, 1); pdfReport.header("值", "value", 0, 5).alignH(HAlign.ALIGN_CENTER).getCell().alignH(HAlign.ALIGN_RIGHT); pdfReport.header("时间", "time", 0, 6); pdfReport.header("图片", "image", 0, 7).width(60).alignH(HAlign.ALIGN_CENTER).getCell() .alignH(HAlign.ALIGN_CENTER).alignV(VAlign.ALIGN_MIDDLE); // 横向打印 pdfReport.getPageSetting().setPrintHorizontal(); pdfReport.group("item1").childGroup("item2"); pdfReport.setCellFormat(new PDFCellValueFormat() { @Override public String format(String fieldName, String oriValue) { if ("value".equals(fieldName)) { return String.format("%.2f", Double.parseDouble(oriValue)).toString(); } else { return oriValue; } } }); JsFileExportResult fileResult = pdfReport.createReport(); return fileResult; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值