Java 根据模板生成 PDF 文件 以及 excel 文件

打印 上一主题 下一主题

主题 546|帖子 546|积分 1638

模板PDF 的字段


引入maven
  1.         
  2.         <dependency>
  3.             <groupId>com.itextpdf</groupId>
  4.             <artifactId>itextpdf</artifactId>
  5.             <version>5.5.13.2</version>
  6.         </dependency>
复制代码
Java 代码
  1. import com.itextpdf.text.DocumentException;
  2. import com.itextpdf.text.Image;
  3. import com.itextpdf.text.pdf.*;
  4. /**
  5.      * 根据pdf模板进行质检报告生成 并上传oss地址  生成二维码在质检报告右上角
  6.      * @param recordDTO
  7.      * @return 返回 oss url
  8.      */
  9.     private String getPdfFilePath(TagPrintingRecordVO recordDTO) {
  10.         String fileName = "";
  11.         PdfReader reader;
  12.         ByteArrayOutputStream bos = new ByteArrayOutputStream();
  13.         try {
  14.             reader = new PdfReader("pdf/template.pdf");
  15.             bos = new ByteArrayOutputStream();
  16.             PdfStamper stamper = new PdfStamper(reader, bos);
  17.             AcroFields form = stamper.getAcroFields();
  18.             Map<String, String> map = new HashMap<>();
  19.             map.put("productName", recordDTO.getProductName());
  20.             map.put("weight", "");
  21.             map.put("specification", recordDTO.getSpecification().toString());
  22.             if(recordDTO.getType() == 1){ // 盘螺
  23.                 map.put("dingchi", "");
  24.                 map.put("deliveryType", "盘螺");
  25.             }else{  // 螺纹
  26.                 map.put("dingchi", recordDTO.getDingchi().toString());
  27.                 map.put("deliveryType", "热轧");
  28.             }
  29.             map.put("batchNumber", recordDTO.getBatchNumber());
  30.             map.put("c", recordDTO.getC().toString());
  31.             map.put("mn", recordDTO.getMn().toString());
  32.             map.put("si", recordDTO.getSi().toString());
  33.             map.put("p", recordDTO.getP().toString());
  34.             map.put("s", recordDTO.getS().toString());
  35.             map.put("ceq", recordDTO.getCeq().toString());
  36.             map.put("yieldTop", recordDTO.getYieldTop());
  37.             map.put("yieldDown", recordDTO.getYieldDown().toString());
  38.             map.put("tensileTop", recordDTO.getTensileTop());
  39.             map.put("tensileDown", recordDTO.getTensileDown().toString());
  40.             map.put("yieldRatioTop", recordDTO.getYieldRatioTop());
  41.             map.put("yieldRatioDown", recordDTO.getYieldRatioDown().toString());
  42.             map.put("bendRatioTop", recordDTO.getBendRatioTop());
  43.             map.put("bendRatioDown", recordDTO.getBendRatioDown().toString());
  44.             map.put("elongationTop", recordDTO.getElongationTop());
  45.             map.put("elongationDown", recordDTO.getElongationDown().toString());
  46.             map.put("agtTop", recordDTO.getAgtTop());
  47.             map.put("agtDown", recordDTO.getAgtDown().toString());
  48.             map.put("gapTop", recordDTO.getGapTop());
  49.             map.put("gapDown", recordDTO.getGapDown().toString());
  50.             map.put("inspector", recordDTO.getInspector());
  51.             map.put("dateValue", recordDTO.getDateValue());
  52.             String filechirldName = DateUtils.getNowTimeStamp().toString();
  53.             fileName = "pdf/" + filechirldName+ ".pdf";
  54.             File pdfFile = new File(fileName);
  55.             pdfFile.createNewFile();
  56.             FileOutputStream fileOutputStream = new FileOutputStream(pdfFile, false);
  57.             this.fillPdfCellForm(map, form);
  58.             // 获取页面大小
  59.             PdfReader pdfReader = new PdfReader("pdf/template.pdf");
  60.             PdfDictionary pageDict = pdfReader.getPageN(1);
  61.             PdfArray mediaBox = pageDict.getAsArray(PdfName.MEDIABOX);
  62.             float pageWidth = mediaBox.getAsNumber(2).floatValue();
  63.             float pageHeight = mediaBox.getAsNumber(3).floatValue();
  64.             // 生成二维码
  65.             BarcodeQRCode qrCode = new BarcodeQRCode("https://XXXX.com/qrcode/"+filechirldName+".pdf", 200, 200, null);
  66.             Image qrCodeImage = qrCode.getImage();
  67.             qrCodeImage.scaleAbsolute(80, 80); // 设置二维码图片的大小
  68.             // 计算二维码的位置(右上角)
  69.             float qrCodeX = pageWidth-80; // 80是右边距
  70.             float qrCodeY = pageHeight-80; // 80是上边距
  71.             qrCodeImage.setAbsolutePosition(qrCodeX, qrCodeY);
  72.             // 将二维码图片添加到 PDF 中
  73.             PdfContentByte contentByte = stamper.getOverContent(1);
  74.             contentByte.addImage(qrCodeImage);
  75.             stamper.setFormFlattening(true);
  76.             stamper.close();
  77.             reader.close();
  78.             fileOutputStream.write(bos.toByteArray());
  79.             fileOutputStream.close();
  80.             // 上传 oss
  81.             Map<String, String> ossMap = AliYunOSSUtils.uploadFile(pdfFile, filechirldName+ ".pdf");
  82.             if(StringUtils.isEmpty(ossMap.get("url"))){
  83.                 throw new RuntimeException("上传oss 失败");
  84.             }
  85.             pdfFile.delete();
  86.             return ossMap.get("url");
  87.         } catch (Exception e) {
  88.             e.printStackTrace();
  89.             throw new RuntimeException("创建PDF失败");
  90.         }
  91.     }
  92.     /**
  93.      * 设置pdf form cell 设置字体
  94.      * @param map
  95.      * @param form
  96.      * @throws IOException
  97.      * @throws DocumentException
  98.      */
  99.     private void fillPdfCellForm(Map<String, String> map, AcroFields form) throws IOException, DocumentException {
  100.         if (baseFont == null) {
  101.             baseFont = BaseFont.createFont("pdf/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  102.         }
  103.         for (Map.Entry entry : map.entrySet()) {
  104.             String key = (String) entry.getKey();
  105.             String value = (String) entry.getValue();
  106.             form.setFieldProperty(key, "textfont", baseFont, null);
  107.             form.setField(key, value);
  108.         }
  109.     }
复制代码
Excel 模板 字段怎样申明


引入maven
  1.         <dependency>
  2.             <groupId>com.alibaba</groupId>
  3.             <artifactId>easyexcel-core</artifactId>
  4.             <version>3.2.0</version>
  5.             <scope>compile</scope>
  6.         </dependency>
复制代码
Java 代码
  1. import com.alibaba.excel.EasyExcel;
  2. import com.alibaba.excel.ExcelWriter;
  3. import com.alibaba.excel.write.metadata.WriteSheet;
  4. /**
  5.      * 导出月均成本
  6.      *
  7.      * @param costBO
  8.      * @return
  9.      */
  10.     @Override
  11.     public String simpleFillExcel(MothlyCostBO costBO) {
  12.         // 获取当天的数据
  13.         ProductionRecordMonthlyCostVO dayCostVO = LedgerReportMapper.ProductionPlanCostLedgerReportDetailByDay(costBO);
  14.         // 当月 月初 到当前日期的 数据
  15.         ProductionRecordMonthlyCostVO monthlyCostVO = LedgerReportMapper.ProductionPlanCostLedgerReportDetailByMonth(costBO);
  16.         BigDecimal dayHost = LedgerReportMapper.ProductionPlanRecordHotShutTimeByDay(costBO);
  17.         BigDecimal monthHost = LedgerReportMapper.ProductionPlanRecordHotShutTimeByMonth(costBO);
  18.         ProductionExcelDownloadVO downloadVO = new ProductionExcelDownloadVO();
  19.         // 每日可以为0
  20.         if (JSONUtil.isNull(dayCostVO)) {
  21.             dayCostVO = new MindaProductionRecordMonthlyCostVO();
  22.             // 设置所有属性为 BigDecimal.ZERO
  23.             dayCostVO.setSumFurnace(BigDecimal.ZERO);
  24.             dayCostVO.setSumSteel(BigDecimal.ZERO);
  25.             dayCostVO.setSumFerromaganese(BigDecimal.ZERO);
  26.             dayCostVO.setSumFurnacePower(BigDecimal.ZERO);
  27.             dayCostVO.setSumFurnaceElectrode(BigDecimal.ZERO);
  28.             dayCostVO.setSumFurnaceLime(BigDecimal.ZERO);
  29.             dayCostVO.setSumCarBon(BigDecimal.ZERO);
  30.             dayCostVO.setSumToner(BigDecimal.ZERO);
  31.             dayCostVO.setSumFurnaceMagnesium(BigDecimal.ZERO);
  32.             dayCostVO.setSumLox(BigDecimal.ZERO);
  33.             dayCostVO.setSumFurnaceNatural(BigDecimal.ZERO);
  34.             dayCostVO.setSumFurnaceThermocouple(BigDecimal.ZERO);
  35.             dayCostVO.setSumFurnaceSampler(BigDecimal.ZERO);
  36.             dayCostVO.setSumRefineLime(BigDecimal.ZERO);
  37.             dayCostVO.setSumSilicoferrite(BigDecimal.ZERO);
  38.             dayCostVO.setSumFluorite(BigDecimal.ZERO);
  39.             dayCostVO.setSumCarburizer(BigDecimal.ZERO);
  40.             dayCostVO.setSumInsulation(BigDecimal.ZERO);
  41.             dayCostVO.setSumSilicon(BigDecimal.ZERO);
  42.             dayCostVO.setSumSiliconAlloy(BigDecimal.ZERO);
  43.             dayCostVO.setSumDeaerator(BigDecimal.ZERO);
  44.             dayCostVO.setSumRefinePower(BigDecimal.ZERO);
  45.             dayCostVO.setSumLiquid(BigDecimal.ZERO);
  46.             dayCostVO.setSumRefineElectrode(BigDecimal.ZERO);
  47.             dayCostVO.setSumRefineNatural(BigDecimal.ZERO);
  48.             dayCostVO.setSumRefineThermocouple(BigDecimal.ZERO);
  49.             dayCostVO.setSumRefineSampler(BigDecimal.ZERO);
  50.             dayCostVO.setSumHighVanadium(BigDecimal.ZERO);
  51.             dayCostVO.setSumCastingPowder(BigDecimal.ZERO);
  52.             dayCostVO.setSumCastingInsulation(BigDecimal.ZERO);
  53.             dayCostVO.setSumSaladOil(BigDecimal.ZERO);
  54.             dayCostVO.setSumCopperPipe(BigDecimal.ZERO);
  55.             dayCostVO.setSumCastingNatural(BigDecimal.ZERO);
  56.             dayCostVO.setSumCastingThermocouple(BigDecimal.ZERO);
  57.             dayCostVO.setSumPowerCasting(BigDecimal.ZERO);
  58.             dayCostVO.setSumProtection(BigDecimal.ZERO);
  59.             dayCostVO.setSumPump(BigDecimal.ZERO);
  60.             dayCostVO.setSumDrive(BigDecimal.ZERO);
  61.             dayCostVO.setSumOxygen(BigDecimal.ZERO);
  62.         }
  63.         // 每月不能为null
  64.         if (monthlyCostVO.getSumDay().compareTo(BigDecimal.ZERO) > 0) {
  65.             if (dayHost == null) {
  66.                 downloadVO = setterDownloadVO(dayCostVO, monthlyCostVO, BigDecimal.ZERO, monthHost, costBO);
  67.             } else {
  68.                 downloadVO = setterDownloadVO(dayCostVO, monthlyCostVO, dayHost, monthHost, costBO);
  69.             }
  70.         }
  71.         // 生成Excel文件
  72.         String templateFileName = "pdf/cost1.xlsx";
  73.         String filechirldName = DateUtils.getNowTimeStamp().toString();
  74.         String outputFileName = "pdf/" + filechirldName + ".xlsx";
  75.         try {
  76.             // 填充数据
  77.             ExcelWriter excelWriter =  EasyExcel.write(outputFileName)
  78.                     .inMemory(true)
  79.                     .withTemplate(templateFileName).build();
  80.             WriteSheet writeSheet = EasyExcel.writerSheet().build();
  81.             excelWriter.fill(downloadVO, writeSheet);
  82.             excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
  83.             Workbook workbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
  84.             workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); // 强制计算公式
  85.             excelWriter.finish();
  86.             File pdfFile = new File(outputFileName);
  87.             // 上传 oss
  88.             Map<String, String> ossMap = AliYunOSSUtils.uploadFile(pdfFile, filechirldName + ".xlsx");
  89.             if (StringUtils.isEmpty(ossMap.get("url"))) {
  90.                 throw new RuntimeException("上传oss 失败");
  91.             }
  92.             pdfFile.delete();
  93.             return ossMap.get("url");
  94.         } catch (Exception e) {
  95.             e.printStackTrace();
  96.             throw new RuntimeException("填充Excel失败");
  97.         }
  98.     }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

杀鸡焉用牛刀

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表