使用Itext导出PDF

简介: 使用Itext导出PDF

导入依赖

 <!--导出pdf所需包-->
 <dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itextpdf</artifactId>
   <version>5.5.10</version>
 </dependency>
 <dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext-asian</artifactId>
   <version>5.2.0</version>
 </dependency>

主要代码

public ResponseEntity<byte[]> exportPDF(String ids, HttpServletResponse response) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 定义全局的字体静态变量
        Font content = null;
        BaseFont bf;
        Font font = null;
        Font totalAmountFont = null;
        Font totalTitleFont = null;
        try {
            //创建字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            content = new Font(bfChinese, 10, Font.NORMAL);
            font = new Font(bf,20,Font.BOLD, BaseColor.BLACK);
            totalTitleFont = new Font(bf,14,Font.BOLD, BaseColor.BLACK);
            totalAmountFont = new Font(bf,14,Font.BOLD, BaseColor.RED);
        } catch (Exception e) {
            log.error("创建字体异常,请检查系统是否有对应字体");
            e.printStackTrace();
        }
        //设置页大小和边距
        Document document = new Document(new RectangleReadOnly(595F, 842F));
        document.setMargins(60, 60, 60, 60);
        try {
            PdfWriter.getInstance(document, baos);
            //打开生成的pdf文件
            document.open();

            String[] split = ids.replaceAll(" ", "").split(",");
            for (String id : split) {
                MonthBillVO monthBillVO = this.getDetailsById(Long.valueOf(id));
                User user = userService.getById(monthBillVO.getUserId());
                Assert.isNull(user, "用户不存在!");
                List<MonthBillDetail> detailList = monthBillVO.getDetailList();
                Assert.isListNull(detailList, "月账单信息为空");

                //设置内容
                Paragraph paragraph = new Paragraph("月对账明细表",font);
                paragraph.setAlignment(1);
                //引用字体
                document.add(paragraph);

                // 设置表格的列宽和列数
                PdfPTable table = new PdfPTable(new float[]{25f,15f,15f,25f,35f,25f});
                table.setSpacingBefore(20f);
                // 设置表格宽度为100%
                table.setWidthPercentage(100.0F);
                table.setHeaderRows(1);
                table.getDefaultCell().setHorizontalAlignment(1);
                PdfPCell cell = null;

                String[] infoTitles = new String[]{"姓名", "性别", "年龄", "护理级别", "床位", "床位类别"};
                for (String title : infoTitles) {
                    cell = new PdfPCell(new Paragraph(title,content));
                    cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(cell);
                }

                List<PdfPCell> oldmanCellList = new ArrayList<>();
                oldmanCellList.add(new PdfPCell(new Paragraph(user.getUserName(), content)));
                oldmanCellList.add(new PdfPCell(new Paragraph(user.getGender() == "1" ? "男":"女", content)));
                oldmanCellList.add(new PdfPCell(new Paragraph(user.getAge().toString(), content)));
                oldmanCellList.add(new PdfPCell(new Paragraph(user.getNursingLevelName(), content)));
                oldmanCellList.add(new PdfPCell(new Paragraph(user.getBedName(), content)));
                if (ObjectUtil.isNotNull(user.getBedId())){
                    R<BcRoomVO> roomResult = remoteRoomService.getRoomNameById(oldman.getBedId().longValue(), SecurityConstants.FROM_IN);
                    if (ObjectUtil.isNotNull(roomResult.getData())){
                        oldmanCellList.add(new PdfPCell(new Paragraph(roomResult.getData().getCategoryName(), content)));
                    }
                }

                oldmanCellList.forEach(item -> {
                    //设置居中
                    item.setHorizontalAlignment(Element.ALIGN_CENTER);
                    item.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    table.addCell(item);
                });

                List<MonthBillChargeTypeEnum> chargeType = MonthBillChargeTypeEnum.getAll();

                Map<Integer, PdfPTable> tableMap = new HashMap<>();
                for (MonthBillChargeTypeEnum monthBillChargeTypeEnum : chargeType) {
                    // 设置表格的列宽和列数
                    PdfPTable table3 = new PdfPTable(new float[]{15f,25f,25f,25f,25f,25f,25f,25f,25f});
                    table3.setSpacingBefore(20f);
                    // 设置表格宽度为100%
                    table3.setWidthPercentage(100.0F);
                    table3.setHeaderRows(1);
                    table3.getDefaultCell().setHorizontalAlignment(1);

                    String[] titles = new String[]{"序号", "费用类别", "明细", "开始时间", "结束时间", "费用总价", "优惠", "结算价", "备注"};
                    for (String title : titles) {
                        cell = new PdfPCell(new Paragraph(title,content));
                        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table3.addCell(cell);
                    }
                    tableMap.put(monthBillChargeTypeEnum.getId(), table3);
                }

                Map<Integer, List<MonthBillDetail>> groupList = detailList.stream().collect(Collectors.groupingBy(MonthBillDetail::getChargeType));

                for (MonthBillChargeTypeEnum type : chargeType) {
                    List<MonthBillDetail> billDetails = groupList.get(type.getId());
                    if (CollectionUtils.isEmpty(billDetails)){
                        continue;
                    }

                    List<PdfPCell> cellList = new ArrayList<>();
                    for (int i=0; i < billDetails.size() ;i++) {
                        MonthBillDetail detail = detailList.get(i);
                        cellList.add(new PdfPCell(new Paragraph(i+1+"", content)));
                        cellList.add(new PdfPCell(new Paragraph(detail.getCostCategoryName(), content)));
                        cellList.add(new PdfPCell(new Paragraph(detail.getItemName(), content)));
                        cellList.add(new PdfPCell(new Paragraph(detail.getStartDate().toLocalDate().toString(), content)));
                        cellList.add(new PdfPCell(new Paragraph(detail.getEndDate().toLocalDate().toString(), content)));
                        cellList.add(new PdfPCell(new Paragraph(detail.getTotalAmount().toString(), content)));
                        cellList.add(new PdfPCell(new Paragraph(detail.getReliefAmount().toString(), content)));
                        cellList.add(new PdfPCell(new Paragraph(detail.getSettlementAmount().toString(), content)));
                        cellList.add(new PdfPCell(new Paragraph(detail.getRemark(), content)));
                    }

                    cellList.forEach(item -> {
                        //设置居中
                        item.setHorizontalAlignment(Element.ALIGN_CENTER);
                        item.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        tableMap.get(type.getId()).addCell(item);
                    });

                }

                document.add(new Paragraph("\n"));
                document.add(new Paragraph("▋ 用户信息",content));
                document.add(table);

                for (Integer key : tableMap.keySet()) {
                    PdfPTable pdfPTable = tableMap.get(key);
                    document.add(new Paragraph("\n"));
                    document.add(new Paragraph("▋ " + MonthBillChargeTypeEnum.getById(key).getValue(), content));
                    int size = pdfPTable.size();
                    if (size > 1){
                        document.add(pdfPTable);
                    }else{
                        Paragraph info = new Paragraph("无", content);
                        info.setAlignment(Element.ALIGN_LEFT);
                        document.add(info);
                    }
                }

                document.add(new Paragraph("\n"));
                // 添加分隔线到文档
                document.add(new LineSeparator());
                Paragraph totalTitle = new Paragraph("合计应收费用", totalTitleFont);
                totalTitle.setAlignment(Element.ALIGN_RIGHT);
                document.add(totalTitle);
                Paragraph totalAmount = new Paragraph("¥ " + monthBillVO.getSettlementAmount(), totalAmountFont);
                totalAmount.setAlignment(Element.ALIGN_RIGHT);
                document.add(totalAmount);
                document.newPage();
            }
            //关闭文档
            document.close();

            // 设置下载文件的响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=example.pdf");

            // 设置文件的MIME类型
            MediaType mediaType = MediaType.APPLICATION_PDF;

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(mediaType)
                    .body(baos.toByteArray());

        } catch (com.itextpdf.text.DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
目录
相关文章
|
2月前
|
Java
java Itext创建pdf
java Itext创建pdf
33 0
|
1月前
|
数据采集 移动开发 前端开发
springboot使用html模版导出pdf文档
springboot使用html模版导出pdf文档
|
2月前
|
Java
itext制作pdf表格
java中使用itext制作pdf表格
|
2月前
|
XML 持续交付 开发工具
SAPGUI 里 ABAP 代码导出成 PDF 格式的隐藏小技巧
SAPGUI 里 ABAP 代码导出成 PDF 格式的隐藏小技巧
27 0
|
2月前
|
测试技术 数据处理 Python
测试报告导出PDF和excel的方法
测试报告导出PDF和excel的方法
|
4月前
|
前端开发 开发工具 git
Django实践-06导出excel/pdf/echarts
Django实践-06导出excel/pdf/echarts
Django实践-06导出excel/pdf/echarts
|
1月前
|
数据挖掘 数据安全/隐私保护 开发者
使用Spire.PDF for Python插件从PDF文件提取文字和图片信息
使用Spire.PDF for Python插件从PDF文件提取文字和图片信息
86 0
|
1月前
|
存储 缓存 Python
如何使用Python抓取PDF文件并自动下载到本地
如何使用Python抓取PDF文件并自动下载到本地
34 0
|
3月前
|
Java API Apache
使用 Apache PDFBox 操作PDF文件
Apache PDFBox库是一个开源的Java工具,专门用于处理PDF文档。它允许用户创建全新的PDF文件,编辑现有的PDF文档,以及从PDF文件中提取内容。此外,Apache PDFBox还提供了一些命令行实用工具。
108 6
|
2月前
|
编解码 数据可视化 数据挖掘
【办公自动化】用Python将PDF文件转存为图片
【办公自动化】用Python将PDF文件转存为图片
67 1