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

来源:https://www.cnblogs.com/depressiom/p/18393147
-Advertisement-
Play Games

模板PDF 的欄位 引入maven <!-- iText for generating PDF files --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5. ...


模板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失敗");
        }
    }

本文來自博客園,作者:depressiom,轉載請註明原文鏈接:https://www.cnblogs.com/depressiom/p/18393147


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 日誌處理logging 一、日誌輸出 日誌預設的輸出等級為:waring級別及以上的等級 修改日誌的預設輸出等級通過logging.basicConfig(level='INFO') 記錄日誌列印時間:logging.basicConfig(format=console_fmt) console_f ...
  • 一、 六大設計原則 1. 單一職責原則:應該有且僅有一個原因引起類的變更 2. 里氏替換原則:子類可替換父類。 a) 子類必須完全實現父類的方法 b) 子類可以有自己的個性 c) 子類實現父類方法時,入參可放大 d) 子類實現父類方法時,輸出參數可縮小 3. 依賴倒置原則:高層模塊不應該依賴底層模塊 ...
  • 事件匯流排(在有些框架中也稱時間聚合器,如Prism的EventAggregater)是訂閱-發佈模式的一種實現,類似觀察者模式,相對於觀察者模式,事件匯流排更靈活,它是一種集中處理事件的模式,允許不同組件之間通信,降低耦合度。 事件匯流排的三要素:事件源(事件的定義)、發佈事件(觸發事件)、訂閱事件(事 ...
  • IT統一運維平臺案例統一運維平臺的架構圖,劃分為三個主要部分:統一運維門戶、報告與決策中心、運維服務調度中心。以下是對每個部分的解析:1. 統一運維門戶這是用戶的統一入口,提供了一系列運維相關的服務和功能,包括:綜合信息發佈:發佈運維相關的信息,如公告、通知等。 自助服務台:用戶可以通過自助服務台提 ...
  • 在 Python 中,內置類型的行為是通過一組特殊的“魔法方法”來實現的,這些魔法方法以雙下劃線開頭和結尾,比如 init 和 str,你可以通過重寫這些魔法方法來定製或擴展內置類型的行為。 ...
  • 【前言】網上各種面試八股文太多太多,但我今年找了好幾個都是很久很久以前的老面試題,老文檔了,和我出去面試市場上面試官問的問題基本上不一樣了,可以說被打了一個措手不及,浪費了好幾個機會,回來又找了好一些資料,以及結合自己最近的面試情況總結了一些心得免費分享給大家!雖然只有幾本電子文檔,但是濃縮的都是精 ...
  • 2018年7月,大三暑假進行時,時間過得飛快,我到這邊實習都已經一個月了。 我在沒工作之前,我老是覺得生產項目的代碼跟我平時自學練的會有很大的區別。 以為生產項目代碼啥的都會規範很多,比如在介面上會做很多安全性的工作(自學練的時候確實學到的類似的案例),代碼設計上會有很多設計模式的應用。 但實際上, ...
  • 為什麼需要SPI機制 SPI和API的區別是什麼 SPI是一種跟API相對應的反向設計思想:API由實現方確定標準規範和功能,調用方無權做任何干預; 而SPI是由調用方確定標準規範,也就是介面,然後調用方依賴此介面,第三方實現此介面,這樣做就可以方便的進行擴展,類似於插件機制,這是SPI出現的需求背 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...