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

模板PDF 的字段

引入maven

        <!-- iText for generating PDF files -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.2</version>
        </dependency>

Java 代码


import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;

/**
     * 根据pdf模板进行质检报告生成 并上传oss地址  生成二维码在质检报告右上角
     * @param recordDTO
     * @return 返回 oss url
     */
    private String getPdfFilePath(TagPrintingRecordVO recordDTO) {
        String fileName = "";
        PdfReader reader;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            reader = new PdfReader("pdf/template.pdf");
            bos = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            Map<String, String> map = new HashMap<>();
            map.put("productName", recordDTO.getProductName());
            map.put("weight", "");
            map.put("specification", recordDTO.getSpecification().toString());
            if(recordDTO.getType() == 1){ // 盘螺
                map.put("dingchi", "");
                map.put("deliveryType", "盘螺");
            }else{  // 螺纹
                map.put("dingchi", recordDTO.getDingchi().toString());
                map.put("deliveryType", "热轧");
            }
            map.put("batchNumber", recordDTO.getBatchNumber());
            map.put("c", recordDTO.getC().toString());
            map.put("mn", recordDTO.getMn().toString());
            map.put("si", recordDTO.getSi().toString());
            map.put("p", recordDTO.getP().toString());
            map.put("s", recordDTO.getS().toString());
            map.put("ceq", recordDTO.getCeq().toString());
            map.put("yieldTop", recordDTO.getYieldTop());
            map.put("yieldDown", recordDTO.getYieldDown().toString());
            map.put("tensileTop", recordDTO.getTensileTop());
            map.put("tensileDown", recordDTO.getTensileDown().toString());
            map.put("yieldRatioTop", recordDTO.getYieldRatioTop());
            map.put("yieldRatioDown", recordDTO.getYieldRatioDown().toString());
            map.put("bendRatioTop", recordDTO.getBendRatioTop());
            map.put("bendRatioDown", recordDTO.getBendRatioDown().toString());
            map.put("elongationTop", recordDTO.getElongationTop());
            map.put("elongationDown", recordDTO.getElongationDown().toString());
            map.put("agtTop", recordDTO.getAgtTop());
            map.put("agtDown", recordDTO.getAgtDown().toString());
            map.put("gapTop", recordDTO.getGapTop());
            map.put("gapDown", recordDTO.getGapDown().toString());
            map.put("inspector", recordDTO.getInspector());
            map.put("dateValue", recordDTO.getDateValue());
            String filechirldName = DateUtils.getNowTimeStamp().toString();
            fileName = "pdf/" + filechirldName+ ".pdf";
            File pdfFile = new File(fileName);
            pdfFile.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(pdfFile, false);
            this.fillPdfCellForm(map, form);

            // 获取页面大小
            PdfReader pdfReader = new PdfReader("pdf/template.pdf");
            PdfDictionary pageDict = pdfReader.getPageN(1);
            PdfArray mediaBox = pageDict.getAsArray(PdfName.MEDIABOX);
            float pageWidth = mediaBox.getAsNumber(2).floatValue();
            float pageHeight = mediaBox.getAsNumber(3).floatValue();

            // 生成二维码
            BarcodeQRCode qrCode = new BarcodeQRCode("https://XXXX.com/qrcode/"+filechirldName+".pdf", 200, 200, null);
            Image qrCodeImage = qrCode.getImage();
            qrCodeImage.scaleAbsolute(80, 80); // 设置二维码图片的大小

            // 计算二维码的位置(右上角)
            float qrCodeX = pageWidth-80; // 80是右边距
            float qrCodeY = pageHeight-80; // 80是上边距
            qrCodeImage.setAbsolutePosition(qrCodeX, qrCodeY);

            // 将二维码图片添加到 PDF 中
            PdfContentByte contentByte = stamper.getOverContent(1);
            contentByte.addImage(qrCodeImage);

            stamper.setFormFlattening(true);
            stamper.close();
            reader.close();

            fileOutputStream.write(bos.toByteArray());
            fileOutputStream.close();
            // 上传 oss
            Map<String, String> ossMap = AliYunOSSUtils.uploadFile(pdfFile, filechirldName+ ".pdf");
            if(StringUtils.isEmpty(ossMap.get("url"))){
                throw new RuntimeException("上传oss 失败");
            }
            pdfFile.delete();
            return ossMap.get("url");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("创建PDF失败");
        }

    }

    /**
     * 设置pdf form cell 设置字体
     * @param map
     * @param form
     * @throws IOException
     * @throws DocumentException
     */
    private void fillPdfCellForm(Map<String, String> map, AcroFields form) throws IOException, DocumentException {

        if (baseFont == null) {
            baseFont = BaseFont.createFont("pdf/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        }
        for (Map.Entry entry : map.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            form.setFieldProperty(key, "textfont", baseFont, null);
            form.setField(key, value);
        }
    }

Excel 模板 字段如何申明

引入maven

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.2.0</version>
            <scope>compile</scope>
        </dependency>

Java 代码

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;


/**
     * 导出月均成本
     *
     * @param costBO
     * @return
     */
    @Override
    public String simpleFillExcel(MothlyCostBO costBO) {
        // 获取当天的数据
        ProductionRecordMonthlyCostVO dayCostVO = LedgerReportMapper.ProductionPlanCostLedgerReportDetailByDay(costBO);
        // 当月 月初 到当前日期的 数据
        ProductionRecordMonthlyCostVO monthlyCostVO = LedgerReportMapper.ProductionPlanCostLedgerReportDetailByMonth(costBO);
        BigDecimal dayHost = LedgerReportMapper.ProductionPlanRecordHotShutTimeByDay(costBO);
        BigDecimal monthHost = LedgerReportMapper.ProductionPlanRecordHotShutTimeByMonth(costBO);

        ProductionExcelDownloadVO downloadVO = new ProductionExcelDownloadVO();

        // 每日可以为0
        if (JSONUtil.isNull(dayCostVO)) {
            dayCostVO = new MindaProductionRecordMonthlyCostVO();
            // 设置所有属性为 BigDecimal.ZERO
            dayCostVO.setSumFurnace(BigDecimal.ZERO);
            dayCostVO.setSumSteel(BigDecimal.ZERO);
            dayCostVO.setSumFerromaganese(BigDecimal.ZERO);
            dayCostVO.setSumFurnacePower(BigDecimal.ZERO);
            dayCostVO.setSumFurnaceElectrode(BigDecimal.ZERO);
            dayCostVO.setSumFurnaceLime(BigDecimal.ZERO);
            dayCostVO.setSumCarBon(BigDecimal.ZERO);
            dayCostVO.setSumToner(BigDecimal.ZERO);
            dayCostVO.setSumFurnaceMagnesium(BigDecimal.ZERO);
            dayCostVO.setSumLox(BigDecimal.ZERO);
            dayCostVO.setSumFurnaceNatural(BigDecimal.ZERO);
            dayCostVO.setSumFurnaceThermocouple(BigDecimal.ZERO);
            dayCostVO.setSumFurnaceSampler(BigDecimal.ZERO);
            dayCostVO.setSumRefineLime(BigDecimal.ZERO);
            dayCostVO.setSumSilicoferrite(BigDecimal.ZERO);
            dayCostVO.setSumFluorite(BigDecimal.ZERO);
            dayCostVO.setSumCarburizer(BigDecimal.ZERO);
            dayCostVO.setSumInsulation(BigDecimal.ZERO);
            dayCostVO.setSumSilicon(BigDecimal.ZERO);
            dayCostVO.setSumSiliconAlloy(BigDecimal.ZERO);
            dayCostVO.setSumDeaerator(BigDecimal.ZERO);
            dayCostVO.setSumRefinePower(BigDecimal.ZERO);
            dayCostVO.setSumLiquid(BigDecimal.ZERO);
            dayCostVO.setSumRefineElectrode(BigDecimal.ZERO);
            dayCostVO.setSumRefineNatural(BigDecimal.ZERO);
            dayCostVO.setSumRefineThermocouple(BigDecimal.ZERO);
            dayCostVO.setSumRefineSampler(BigDecimal.ZERO);
            dayCostVO.setSumHighVanadium(BigDecimal.ZERO);
            dayCostVO.setSumCastingPowder(BigDecimal.ZERO);
            dayCostVO.setSumCastingInsulation(BigDecimal.ZERO);
            dayCostVO.setSumSaladOil(BigDecimal.ZERO);
            dayCostVO.setSumCopperPipe(BigDecimal.ZERO);
            dayCostVO.setSumCastingNatural(BigDecimal.ZERO);
            dayCostVO.setSumCastingThermocouple(BigDecimal.ZERO);
            dayCostVO.setSumPowerCasting(BigDecimal.ZERO);
            dayCostVO.setSumProtection(BigDecimal.ZERO);
            dayCostVO.setSumPump(BigDecimal.ZERO);
            dayCostVO.setSumDrive(BigDecimal.ZERO);
            dayCostVO.setSumOxygen(BigDecimal.ZERO);
        }
        // 每月不能为null
        if (monthlyCostVO.getSumDay().compareTo(BigDecimal.ZERO) > 0) {
            if (dayHost == null) {
                downloadVO = setterDownloadVO(dayCostVO, monthlyCostVO, BigDecimal.ZERO, monthHost, costBO);
            } else {
                downloadVO = setterDownloadVO(dayCostVO, monthlyCostVO, dayHost, monthHost, costBO);
            }
        }


        // 生成Excel文件
        String templateFileName = "pdf/cost1.xlsx";

        String filechirldName = DateUtils.getNowTimeStamp().toString();
        String outputFileName = "pdf/" + filechirldName + ".xlsx";
        try {
            // 填充数据
            ExcelWriter excelWriter =  EasyExcel.write(outputFileName)
                    .inMemory(true)
                    .withTemplate(templateFileName).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            excelWriter.fill(downloadVO, writeSheet);
            excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
            Workbook workbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
            workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); // 强制计算公式
            excelWriter.finish();

            File pdfFile = new File(outputFileName);
            // 上传 oss
            Map<String, String> ossMap = AliYunOSSUtils.uploadFile(pdfFile, filechirldName + ".xlsx");
            if (StringUtils.isEmpty(ossMap.get("url"))) {
                throw new RuntimeException("上传oss 失败");
            }
            pdfFile.delete();
            return ossMap.get("url");

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("填充Excel失败");
        }
    }