首页 > 编程语言 >Java 根据模板生成 PDF 文件 以及 excel 文件

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

时间:2024-09-02 17:37:30浏览次数:10  
标签:文件 recordDTO Java BigDecimal dayCostVO excel map ZERO put

模板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 模板 字段如何申明

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失败");
        }
    }

标签:文件,recordDTO,Java,BigDecimal,dayCostVO,excel,map,ZERO,put
From: https://www.cnblogs.com/depressiom/p/18393147

相关文章

  • java定义通用返回结果类ResultVO使用示例详解
    java定义通用返回结果类ResultVO使用示例详解定义通用返回结果类定义ResultVO类,作返回给前端的对象结构,主要有4个字段code:错误码data:内容message:消息description:具体描述importlombok.Data;importjava.io.Serializable;/***通用返回结果类*@param<T>*/@D......
  • 河北成人高等教育在线刷课脚本-JavaScript编写
    脚本学习网站:河北成人高等教育在线:http://www.hbcjpt.com/portal/脚本地址:河北成人高等教育在线刷课脚本-刷课脚本教程1.插件安装(以MicrosoftEdge浏览器为例)打开最中间那个蓝色绿色的浏览器,谷歌之类的浏览器也可以点击屏幕右上角三个点,图示位置,然后点击扩展点击获取......
  • java中的synchronized
    介绍Java中的synchronized关键字是一种内置的同步机制,用于实现线程之间的互斥,以确保多个线程在同一时刻只能有一个线程访问特定的代码段或对象。synchronized可以用于方法或代码块,从而实现对共享资源的安全访问。前言需要明确的是,锁是针对对象而言的,以下场景实际上都是在描述外......
  • delphi开发Excel用户定义函数
    在Delphi中开发Excel用户定义函数(User-DefinedFunction,UDF)通常涉及到以下几个关键步骤:1.**创建DLL文件**-使用Delphi编写一个动态链接库(DLL),其中包含要作为ExcelUDF的函数。函数必须遵循特定的签名规范,以便Excel能够识别和调用。示例UDF函数:```delphilibr......
  • 奥鹏教师教育网刷课脚本-JavaScript编写
    脚本学习网站:奥鹏教师教育网:http://www.ourteacher.com.cn/脚本地址:奥鹏教师教育网-刷课脚本教程1.插件安装(以MicrosoftEdge浏览器为例)打开最中间那个蓝色绿色的浏览器,谷歌之类的浏览器也可以点击屏幕右上角三个点,图示位置,然后点击扩展点击获取扩展搜索Tampermonk......
  • 青海专业技术人员学习网刷课脚本-JavaScript编写
    脚本学习网站:青海省专业技术人员继续教育平台:https://qh.ctet.org.cn青海专业技术人员学习网:https://qinghai.qgzjrcw.com.cn脚本地址:青海专业技术人员学习网-刷课脚本教程1.插件安装(以MicrosoftEdge浏览器为例)打开最中间那个蓝色绿色的浏览器,谷歌之类的浏览器也可以......
  • 程序员必备Java八股文合集
    1、Java线程具有五中基本状态(1)新建状态(New): 当线程对象对创建后,即进入了新建状态,如:Threadt=newMyThread();(2)就绪状态(Runnable):当调用线程对象的start()方法(t.start();),线程即进入就绪状态。处于就绪状态的线程,只是说明此线程已经做好了准备,随时等待CPU调度执行,并不......
  • java集合练习02
    使用ArrayList完成对对象Car{name,price}的各种操作1.add:添加单个元素2.remove:删除指定元素3.contains:查找元素是否存在•4.size:获取元素个数5.isEmpty:判断是否为空6.Clear:清空7.addAll:添加多个元素8.containsAll:查找多个元素是否都存在9.removeAll:删除多个元素1......
  • Java基础(7)- Java代码笔记4
    目录一、面向对象1.面向对象介绍2.类的介绍和定义3.对象的使用4.匿名对象5.面向对象内存图a.一个对像内存图b.两个对象内存图c.两个对象指向同一片空间内存图6.成员变量和局部变量的区别7.MyDate类二、封装1.封装介绍2.private关键字3.get&set方法4.this关键字......
  • IDA反编译dll库时导入C++头文件
    引言有时候,可能因为硬盘损坏等等原因,自己曾经写的动态链接库源码丢失了,幸好对应的头文件得以保留了下来,这个动态链接库主要是某种算法的实现,并没有继承其他的一些类库,比如MFC之类的,而自己对算法的实现已经忘得差不多了,而突然又需要该算法的实现过程,那么有什么办法可以帮助......