瀏覽代碼

excelToPdf

lyhzzz 2 年之前
父節點
當前提交
025dcb73ec

二進制
output/ExcelToPdf


+ 6 - 3
pom.xml

@@ -176,10 +176,13 @@
             <version>5.2.0</version>
         </dependency>
 
-
+        <dependency>
+            <groupId>com.aspose</groupId>
+            <artifactId>aspose-cells</artifactId>
+            <version>22.7</version>
+        </dependency>
     </dependencies>
 
-
     <build>
         <plugins>
             <plugin>
@@ -205,4 +208,4 @@
         </plugins>
 
     </build>
-</project>
+  </project>

+ 1 - 1
src/main/java/com/fdkankan/sale/common/FilePath.java

@@ -3,6 +3,6 @@ package com.fdkankan.sale.common;
 public class FilePath {
 
     public static String common = "common";
-    public static String file_path = "/home/backend/4dkankan_v4/sale/file/";
+    public static String file_path = "G:/home/backend/4dkankan_v4/sale/file/";
     public static String oss_file_path = "sale/file/%s/%s";
 }

+ 2 - 2
src/main/java/com/fdkankan/sale/controller/RepairInfoController.java

@@ -76,10 +76,10 @@ public class RepairInfoController extends BaseController{
                             @RequestParam(required = false,defaultValue = "0") Integer type){
         OrderListVo orderListVo = repairInfoService.getExportVo(repairId);
         if(type == 0){
-            excelUtil.listFill(response,"四维时代服务清单",orderListVo,orderListVo.getPriceListExcelVos(),orderListVo.getExportImg(),type);
+            excelUtil.listFill(response,repairId+"_报价单",orderListVo,orderListVo.getPriceListExcelVos(),orderListVo.getExportImg(),type);
         }
         if(type == 1){
-            excelUtil.listFill(response,"维修服务单",orderListVo,orderListVo.getPriceListExcelVos(),orderListVo.getExportImg(),type);
+            excelUtil.listFill(response,repairId+"_维修工单",orderListVo,orderListVo.getPriceListExcelVos(),orderListVo.getExportImg(),type);
         }
     }
 

+ 98 - 26
src/main/java/com/fdkankan/sale/util/MyExcelUtil.java

@@ -3,6 +3,8 @@ package com.fdkankan.sale.util;
 import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.util.ObjectUtil;
+import com.alibaba.excel.read.metadata.ReadSheet;
+import com.alibaba.excel.write.handler.SheetWriteHandler;
 import com.fdkankan.fyun.face.FYunFileServiceInterface;
 import com.fdkankan.sale.common.CacheUtil;
 import com.fdkankan.sale.common.FilePath;
@@ -10,6 +12,16 @@ import com.fdkankan.sale.entity.Customer;
 import com.fdkankan.sale.entity.PriceList;
 import com.fdkankan.sale.service.IPriceListService;
 import com.fdkankan.sale.util.pdf.ExportImg;
+import com.fdkankan.sale.util.pdf.TestForExcel2PDF;
+import javassist.expr.FieldAccess;
+import org.apache.poi.ss.usermodel.ClientAnchor;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
+import org.apache.poi.ss.usermodel.WorkbookFactory;
+import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
+import org.apache.poi.xssf.usermodel.XSSFDrawing;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.io.ClassPathResource;
 import com.alibaba.excel.EasyExcel;
@@ -21,10 +33,7 @@ import org.springframework.stereotype.Component;
 import javax.imageio.ImageIO;
 import javax.servlet.http.HttpServletResponse;
 import java.awt.image.BufferedImage;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
+import java.io.*;
 import java.net.URLEncoder;
 import java.util.*;
 
@@ -37,15 +46,8 @@ public class MyExcelUtil {
 
     //根据模板导出excel
     public void listFill(HttpServletResponse response, String excelName, Object obj, Object obj2, ExportImg exportImg,Integer type) {
-        response.setContentType("application/vnd.ms-excel");
-        response.setCharacterEncoding("utf-8");
         String fileName = excelName  + ".xlsx";
-        try {
-            fileName = URLEncoder.encode(fileName, "UTF-8");
-        } catch (UnsupportedEncodingException e) {
-            e.printStackTrace();
-        }
-        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
+
         // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
         // 填充list 的时候还要注意 模板中{.} 多了个点 表示list
         //获取文件路径
@@ -62,18 +64,22 @@ public class MyExcelUtil {
         if(!file.exists()){
             fYunFileServiceInterface.downloadFile(ossPath,localPath );
         }
+        String ossPathImage =   String.format(FilePath.oss_file_path,FilePath.common,"logo.png");
+        String localPathImage = FilePath.file_path + FilePath.common +"/"  + "logo.png";
+        File fileImage = new File(localPathImage);
+        if(!fileImage.exists()){
+            fYunFileServiceInterface.downloadFile(ossPathImage,localPathImage );
+        }
         String templateFileName = file.getPath();
 
+        String localFilePath = FilePath.file_path + FilePath.common + "/" + fileName;
+        File localFile = new File(localFilePath);
         ExcelWriter excelWriter = null;
-        try {
-            excelWriter = EasyExcel.write(response.getOutputStream())
-                    .withTemplate(templateFileName)
-                    //调用合并策略
-                    //.registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex, mergeColumeIndex))
-                    .build();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
+        excelWriter = EasyExcel.write(localFile)
+                .withTemplate(templateFileName)
+                //调用合并策略
+                //.registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex, mergeColumeIndex))
+                .build();
         WriteSheet writeSheet = EasyExcel.writerSheet().build();
         // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行,然后下面的数据往后移动。默认 是false,会直接使用下一行,如果没有则创建。
         // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了,所以慎用
@@ -91,16 +97,42 @@ public class MyExcelUtil {
             //imageHandleByParam(map);
             excelWriter.fill(exportImg, fillConfig, writeSheet);
         }
+
         assert excelWriter != null;
         excelWriter.finish();
+        this.addImage(localFilePath,localPathImage);
+        TestForExcel2PDF.excelToPdf(localFilePath,localFilePath.replace(".xlsx",".pdf"));
+
+        response.setContentType("application/force-download");
+        response.setCharacterEncoding("utf-8");
+        try {
+            fileName = URLEncoder.encode(fileName, "UTF-8");
+        } catch (UnsupportedEncodingException e) {
+            e.printStackTrace();
+        }
+        response.setHeader("Content-disposition", "attachment;filename=" + fileName.replace(".xlsx",".pdf"));
+
+        // 以流的形式下载文件。
+        try {
+            InputStream fis = new BufferedInputStream(new FileInputStream(localFilePath.replace(".xlsx",".pdf")));
+            byte[] buffer = new byte[fis.available()];
+            fis.read(buffer);
+            fis.close();
+            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
+            toClient.write(buffer);
+            toClient.flush();
+            toClient.close();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
 
     }
 
-    /**
-     * 图片处理
-     *
-     * @param param
-     */
+        /**
+         * 图片处理
+         *
+         * @param param
+         */
     private void imageHandleByParam(Map<String, Object> param) {
         for (Map.Entry<String, Object> entry : param.entrySet()) {
             String mapKey = entry.getKey();
@@ -135,5 +167,45 @@ public class MyExcelUtil {
         }
     }
 
+    public  void  addImage(String filePath,String imagePath)  {
+        FileOutputStream fileOut  =   null ;
+        BufferedImage bufferImg  = null ;
+        try {
+            // 先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
+            ByteArrayOutputStream byteArrayOut  =   new  ByteArrayOutputStream();
+            bufferImg  =  ImageIO.read( new  File( imagePath ));
+            ImageIO.write(bufferImg, "png" ,byteArrayOut);
+
+            // 创建一个工作薄
+            XSSFWorkbook wb  =   new  XSSFWorkbook(new FileInputStream(new File(filePath)));
+            XSSFSheet sheet1  =  wb.getSheetAt(0);
+            // XSSFRow row = sheet1.createRow(2);
+            int lastRowNum = sheet1.getLastRowNum();
+
+            XSSFDrawing patriarch  =  sheet1.createDrawingPatriarch();
+            XSSFClientAnchor anchor  =   new  XSSFClientAnchor( 0 , 0 , 512 , 255 ,( short )  6 , lastRowNum-6 ,( short ) 7 , lastRowNum -4 );
+            // 插入图片
+            patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),XSSFWorkbook.PICTURE_TYPE_PNG));
+
+            fileOut =  new FileOutputStream( filePath );
+            // 写入excel文件
+            wb.write(fileOut);
+            fileOut.close();
+
+        } catch (IOException io) {
+            io.printStackTrace();
+            System.out.println( " io erorr :   " +  io.getMessage());
+        }   finally {
+            if  (fileOut  !=   null ) {
+                try   {
+                    fileOut.close();
+                }
+                catch  (IOException e) {
+                    //  TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+            }
+        }
+    }
 
 }

+ 179 - 0
src/main/java/com/fdkankan/sale/util/pdf/TestForExcel2PDF.java

@@ -0,0 +1,179 @@
+package com.fdkankan.sale.util.pdf;
+
+import com.aspose.cells.*;
+import com.itextpdf.awt.geom.Rectangle2D;
+import com.itextpdf.text.BaseColor;
+import com.itextpdf.text.pdf.PdfContentByte;
+import com.itextpdf.text.pdf.PdfReader;
+import com.itextpdf.text.pdf.PdfStamper;
+import com.itextpdf.text.pdf.parser.ImageRenderInfo;
+import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
+import com.itextpdf.text.pdf.parser.RenderListener;
+import com.itextpdf.text.pdf.parser.TextRenderInfo;
+
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+public class TestForExcel2PDF {
+
+    public static void excelToPdf(String xlsxPath,String pdfPath) {
+        excel2pdf(xlsxPath, pdfPath+".sy");
+        replaceStr(pdfPath+".sy",pdfPath,"Evaluation Only. Created with Aspose.Cells for Java.Copyright 2003 - 2022 Aspose Pty Ltd.");
+    }
+
+    private static void replaceStr(String src, String dest, String replaceStr) {
+        try {
+            List<String> resu = new ArrayList<>();
+            PdfReader reader = new PdfReader(src);
+            //获取指定文字的坐标(就是上一步生成的pdf水印)
+            getKeyWords(reader,replaceStr,resu);
+            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
+            for (int i = 1; i <= resu.size(); i++) {
+                String xy = resu.get(i - 1);
+                PdfContentByte canvas = stamper.getOverContent(i);
+                canvas.saveState();
+                //设置颜色
+                canvas.setColorFill(BaseColor.WHITE);
+                //解析坐标
+                double x = Double.valueOf(xy.split("--")[0]);
+                double y = Double.valueOf(xy.split("--")[1]) - 10;
+                //后面2个参数分别是宽高
+                canvas.rectangle(x, y, 450, 100);
+                canvas.fill();
+                canvas.restoreState();
+            }
+            stamper.close();
+            reader.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 获取指定文字的坐标
+     */
+    public static void getKeyWords(PdfReader pdfReader, String replaceStr,List<String> resu ) {
+        try {
+            int pageNum = pdfReader.getNumberOfPages();
+            PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(
+                    pdfReader);
+            for (int i = 1; i <= pageNum; i++) {
+                pdfReaderContentParser.processContent(i, new RenderListener() {
+                    @Override
+                    public void renderText(TextRenderInfo textRenderInfo) {
+                        String text = textRenderInfo.getText(); // 整页内容
+                        if (null != text && text.contains(replaceStr)) {
+                            Rectangle2D.Float boundingRectange = textRenderInfo
+                                    .getBaseline().getBoundingRectange();
+                            String xy = boundingRectange.x + "--" + boundingRectange.y;
+                            resu.add(xy);
+                        }
+                    }
+                    @Override
+                    public void renderImage(ImageRenderInfo arg0) {
+                    }
+                    @Override
+                    public void endTextBlock() {
+                    }
+                    @Override
+                    public void beginTextBlock() {
+                    }
+                });
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 获取license 去除水印
+     * @return
+     */
+    public static boolean getLicense() {
+        boolean result = false;
+        try {
+//            InputStream is = TestForExcel2PDF.class.getClassLoader().getResourceAsStream("\\license.xml");
+//            License aposeLic = new License();
+//            aposeLic.setLicense(is);
+            result = true;
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return result;
+    }
+
+    /**
+     * excel 转为pdf 输出。
+     *
+     * @param sourceFilePath  excel文件
+     * @param desFilePathd  pad 输出文件目录
+     */
+    public static void excel2pdf(String sourceFilePath, String desFilePathd ){
+        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
+            return;
+        }
+        try {
+            Workbook wb = new Workbook(sourceFilePath);// 原始excel路径
+
+            FileOutputStream fileOS = new FileOutputStream(desFilePathd);
+            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
+            pdfSaveOptions.setOnePagePerSheet(true);
+
+
+            int[] autoDrawSheets={3};
+            //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
+//            autoDraw(wb,autoDrawSheets);
+
+            int[] showSheets={0};
+            //隐藏workbook中不需要的sheet页。
+            printSheetPage(wb,showSheets);
+            wb.save(fileOS, pdfSaveOptions);
+            fileOS.flush();
+            fileOS.close();
+            System.out.println("完毕");
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    /**
+     * 设置打印的sheet 自动拉伸比例
+     * @param wb
+     * @param page 自动拉伸的页的sheet数组
+     */
+    public static void autoDraw(Workbook wb,int[] page){
+        if(null!=page&&page.length>0){
+            for (int i = 0; i < page.length; i++) {
+                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
+                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
+            }
+        }
+    }
+
+
+    /**
+     * 隐藏workbook中不需要的sheet页。
+     * @param wb
+     * @param page 显示页的sheet数组
+     */
+    public static void printSheetPage(Workbook wb,int[] page){
+        for (int i= 1; i < wb.getWorksheets().getCount(); i++)  {
+            wb.getWorksheets().get(i).setVisible(false);
+        }
+        if(null==page||page.length==0){
+            wb.getWorksheets().get(0).setVisible(true);
+        }else{
+            for (int i = 0; i < page.length; i++) {
+                wb.getWorksheets().get(i).setVisible(true);
+            }
+        }
+    }
+
+}
+
+