Browse Source

fix 修改批量下载接口,新增创建PDF文件

DYH2020 2 years ago
parent
commit
0585a887fd

+ 7 - 0
pom.xml

@@ -194,6 +194,13 @@
             <artifactId>commons-io</artifactId>
             <version>2.4</version>
         </dependency>
+        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
+        <dependency>
+            <groupId>com.itextpdf</groupId>
+            <artifactId>itextpdf</artifactId>
+            <version>5.5.13.3</version>
+        </dependency>
+
     </dependencies>
     <profiles>
         <profile>

+ 159 - 0
src/main/java/com/ywt/mg/core/utils/GeneratePdf.java

@@ -0,0 +1,159 @@
+package com.ywt.mg.core.utils;
+
+/**
+ * @author daiyihua
+ * @create 2023-02-27 11:01
+ * @program download_service
+ * @description 创建PDF
+ **/
+
+import com.itextpdf.text.*;
+import com.itextpdf.text.Font;
+import com.itextpdf.text.Image;
+import com.itextpdf.text.pdf.ColumnText;
+import com.itextpdf.text.pdf.PdfContentByte;
+import com.itextpdf.text.pdf.PdfWriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.List;
+
+public class GeneratePdf {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(GeneratePdf.class);
+
+    public void handleText(PdfWriter writer, String content, String color,
+                           float x, float y, float z) {
+        PdfContentByte canvas = writer.getDirectContent();
+        Phrase phrase = new Phrase(content);
+        if (color != null) {
+            phrase = new Phrase(content, FontFactory.getFont(FontFactory.COURIER, 12, Font.NORMAL));
+        }
+        ColumnText.showTextAligned(canvas, Element.ALIGN_UNDEFINED, phrase, x, y, z);
+    }
+
+    public File Pdf(String imagePath, String mOutputPdfFileName) {
+        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
+        try {
+            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(
+                    mOutputPdfFileName));
+            doc.open();
+
+            doc.newPage();
+            Image png1 = Image.getInstance(imagePath);
+            float height = png1.getHeight();
+            float width = png1.getWidth();
+            int percent = this.getPercent2(height, width);
+            png1.setAlignment(Image.MIDDLE);
+            png1.setAlignment(Image.TEXTWRAP);
+            png1.scalePercent(percent + 3);
+            doc.add(png1);
+            this.handleText(writer, "This is a test", "red", 400, 725, 0);
+            doc.close();
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (DocumentException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+
+        File mOutputPdfFile = new File(mOutputPdfFileName);
+        if (!mOutputPdfFile.exists()) {
+            mOutputPdfFile.deleteOnExit();
+            return null;
+        }
+        return mOutputPdfFile;
+    }
+
+    public void insertText(String content, String mOutputPdfFileName) {
+        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
+        try {
+            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
+            doc.open();
+            doc.newPage();
+            Phrase phrase = new Phrase(content);
+            doc.add(phrase);
+            doc.close();
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (DocumentException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 创建pdf,添加文字和图片
+     *
+     * @param content            文字
+     * @param imagePathList      图片list
+     * @param mOutputPdfFileName 文件名
+     */
+    public void Pdf(String content, List<String> imagePathList, String mOutputPdfFileName) {
+        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
+        try {
+            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
+            doc.open();
+            doc.newPage();
+            Phrase phrase = new Phrase(content);
+            doc.add(phrase);
+            for (String imagePath : imagePathList) {
+                doc.newPage();
+                Image png1 = Image.getInstance(imagePath);
+                float height = png1.getHeight();
+                float width = png1.getWidth();
+                int percent = this.getPercent2(height, width);
+                png1.setAlignment(Image.MIDDLE);
+                png1.setAlignment(Image.TEXTWRAP);
+                png1.scalePercent(percent + 3);
+                doc.add(png1);
+            }
+            doc.close();
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (DocumentException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public int getPercent1(float h, float w) {
+        int p = 0;
+        float p2 = 0.0f;
+        if (h > w) {
+            p2 = 297 / h * 100;
+        } else {
+            p2 = 210 / w * 100;
+        }
+        p = Math.round(p2);
+        return p;
+    }
+
+    private int getPercent2(float h, float w) {
+        int p = 0;
+        float p2 = 0.0f;
+        p2 = 530 / w * 100;
+        p = Math.round(p2);
+        return p;
+    }
+/*
+    public static void main(String[] args) {
+        GeneratePdf gp = new GeneratePdf();
+        String pdfUrl = "C:\\pdf.pdf";
+        File file = gp
+                .Pdf("C:\\683.JPG",pdfUrl);
+        try {
+            file.createNewFile();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+*/
+}

+ 5 - 0
src/main/java/com/ywt/mg/domain/models/ConstantDef.java

@@ -131,4 +131,9 @@ public class ConstantDef {
      * 对应ywt_drug库pharmacy表id=20的广三药房ID
      */
     public static final int GUANGSAN_ID = 20;
+
+    /**
+     * 企业资料申请
+     */
+    public static final String MARKER_PROJECT_PATH_PUBLIC = "/up/marketting_project/public";
 }

+ 127 - 5
src/main/java/com/ywt/mg/services/enterprise/ApplyProjectService.java

@@ -4,11 +4,15 @@ import com.ywt.mg.configs.DomainConfigurer;
 import com.ywt.mg.core.SqlHelper;
 import com.ywt.mg.core.utils.Checker;
 import com.ywt.mg.core.utils.FileUtil;
+import com.ywt.mg.core.utils.GeneratePdf;
 import com.ywt.mg.core.utils.ZipFileUtil;
 import com.ywt.mg.core.utils.serializers.JsonSerializer;
 import com.ywt.mg.domain.entities.*;
+import com.ywt.mg.domain.models.ConstantDef;
 import com.ywt.mg.params.enterprise.marketting.BatchDownloadFilesRequest;
 import com.ywt.mg.services.AuthService;
+import com.ywt.mg.web.DataResponse;
+import com.ywt.mg.web.common.FileSrv;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -17,6 +21,7 @@ import org.springframework.stereotype.Service;
 import javax.servlet.http.HttpServletResponse;
 import java.io.*;
 import java.net.URL;
+import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -43,6 +48,8 @@ public class ApplyProjectService {
     private DomainConfigurer domainConfigurer;
     @Autowired
     private MarketingProjectRepository marketingProjectRepository;
+    @Autowired
+    private FileSrv fileSrv;
 
     public static final String APPLY_PROJECT_FILE_PATH = "./apply_project_file/files/";
     public static final String APPLY_PROJECT_ROOT_PATH = "./apply_project_file/";
@@ -60,6 +67,8 @@ public class ApplyProjectService {
      * @return
      */
     public void batchDownloadFiles(BatchDownloadFilesRequest request, HttpServletResponse response) {
+        String filePrefix = "";
+        String rootPrefix = "";
         try {
             // 1、先根据从前端选择的条件去数据库查找对应的记录
             Map<String, String> item = new HashMap<>();
@@ -67,6 +76,10 @@ public class ApplyProjectService {
             item.put("下载.jpg", "https://ywt-files.oss-cn-shenzhen.aliyuncs.com//up/marketting_project/public/9-bb077b3512074ddaae0a12d797f20d02.jpg");
             item.put("测试文档.pdf", "https://ywt-files.oss-cn-shenzhen.aliyuncs.com//up/marketting_project/public/9-1b9a0a24f2be4cef882a22d1a5750ae5.pdf");
 
+            int number = (int) (Math.random() * 1000);
+            filePrefix = APPLY_PROJECT_FILE_PATH + number + "/";
+            rootPrefix = APPLY_PROJECT_ROOT_PATH + number + "/";
+
             // 2、遍历记录去下载对应的文件到服务器;
             List<String> fileUrl = new ArrayList<>();
             for (Map.Entry<String, String> entry : item.entrySet()) {
@@ -75,7 +88,7 @@ public class ApplyProjectService {
                     continue;
                 }
                 String urlLink = entry.getValue();
-                String pathName = APPLY_PROJECT_FILE_PATH + entry.getKey();
+                String pathName = filePrefix + entry.getKey();
                 // 下载单个文件
                 downloadSingleFile(urlLink, pathName);
                 fileUrl.add(pathName);
@@ -87,15 +100,16 @@ public class ApplyProjectService {
                 zipFileName += request.getUploadTimeStart().replace("-", "") + "~" + request.getUploadTimeEnd().replace("-", "");
             }
             zipFileName += ".zip";
-            ZipFileUtil.stringFileUrlToZip(APPLY_PROJECT_ROOT_PATH + zipFileName, fileUrl);
+            ZipFileUtil.stringFileUrlToZip(rootPrefix + zipFileName, fileUrl);
 
             // 4、将打包的文件传给客户端
-            downFile(response, APPLY_PROJECT_ROOT_PATH, zipFileName);
+            downFile(response, rootPrefix, zipFileName);
         } catch (Exception e) {
             logger.error("ApplyProjectService#batchDownloadFiles(request:{}){}", JsonSerializer.toJson(request), e.getMessage(), e);
         } finally {
             // 5、删掉之前所有的文件;
-            FileUtil.deleteFolders(APPLY_PROJECT_ROOT_PATH);
+            FileUtil.deleteFolders(filePrefix);
+            FileUtil.deleteFolders(rootPrefix);
         }
     }
 
@@ -147,7 +161,7 @@ public class ApplyProjectService {
                 // 获取文件输出IO流
                 OutputStream outs = response.getOutputStream();
                 BufferedOutputStream bouts = new BufferedOutputStream(outs);
-                response.addHeader("content-disposition", "attachment;filename="+ new String(str.getBytes(), "iso-8859-1"));
+                response.addHeader("content-disposition", "attachment;filename=" + new String(str.getBytes(), "iso-8859-1"));
                 int bytesRead = 0;
                 //1M逐个读取
                 byte[] bytes = new byte[1024 * 1024];
@@ -169,4 +183,112 @@ public class ApplyProjectService {
         }
     }
 
+    /**
+     * 创建PDF文件:
+     *
+     * 1、先根据从前端选择的条件去数据库查找对应的记录
+     * 2、遍历记录去下载对应的文件到服务器;
+     * 3、生成pdf
+     * 4、上传到oss
+     * 5、删掉之前所有的文件;
+     *
+     * @param request
+     */
+    public void createPDF(BatchDownloadFilesRequest request) {
+        String filePrefix = "";
+        String rootPrefix = "";
+        try {
+            // 1、先根据从前端选择的条件去数据库查找对应的记录
+            Map<String, String> item = new HashMap<>();
+            item.put("1", "c23401c928d841e79be95479d8e68144jpeg");
+            item.put("2", "05c8799a202e45ebbedd3e81c790fc87jpeg");
+            item.put("3", "266d03218ca94683a022c6502f59357cjpeg");
+
+            item.put("4", "c6ec2e8f87194190a75012c52b7b29ebjpeg");
+            item.put("5", "0f7e4fccaebf4c5581d5742c48b5209ejpeg");
+            item.put("6", "ec48ac7b51994507a31a4e8a90aa56a6jpeg");
+
+            item.put("7", "dccf09a43dfb449f91ad26fce588fcc6jpeg");
+            item.put("8", "89d6df3dd1cd4c29937e1f46899ac6e4jpeg");
+            item.put("9", "ff31f865218240c5a37729352296ea25jpeg");
+
+            int number = (int) (Math.random() * 1000);
+            filePrefix = APPLY_PROJECT_FILE_PATH + number + "/";
+            rootPrefix = APPLY_PROJECT_ROOT_PATH + number + "/";
+
+            // 2、遍历记录去下载对应的文件到服务器;
+            List<String> fileUrl = new ArrayList<>();
+            for (Map.Entry<String, String> entry : item.entrySet()) {
+                logger.info(entry.getKey() + "--->" + entry.getValue());
+                if (Checker.isNone(entry.getKey()) || Checker.isNone(entry.getValue())) {
+                    continue;
+                }
+                String urlLink = "up/marketting_project" + "/" + entry.getValue();
+                String pathName = filePrefix + entry.getKey() + ".jpg";
+                // 下载单个文件
+                downloadSingleFileFromGrpc(urlLink, pathName);
+                fileUrl.add(pathName);
+            }
+            // 3、生成pdf
+            String word = "12345678901234567890312345678901234567890123456789012345678901啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦啦!!!!234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
+            String fileName = "资料.pdf";
+            String pdfPath = rootPrefix + fileName;
+            createPDF(word, fileUrl, pdfPath);
+
+            // 4、上传到OSS
+            DataResponse dataResponse = fileSrv.localFileUploadToOss(rootPrefix, fileName, ConstantDef.MARKER_PROJECT_PATH_PUBLIC);
+            logger.info("ApplyProjectService#createPDF ossUrl:-->" + dataResponse.getData());
+        } catch (Exception e) {
+            logger.error("ApplyProjectService#batchDownloadFiles(request:{}){}", JsonSerializer.toJson(request), e.getMessage(), e);
+        } finally {
+            // 5、删掉之前所有的文件;
+            FileUtil.deleteFolders(rootPrefix);
+            FileUtil.deleteFolders(filePrefix);
+        }
+    }
+
+    private void createPDF(String word, List<String> fileUrl, String pdfPath) {
+        FileUtil.createFoldersIfNotExit(pdfPath);
+        GeneratePdf gp = new GeneratePdf();
+        gp.Pdf(word, fileUrl, pdfPath);
+    }
+
+    /**
+     * 下载单个文件到服务器
+     *
+     * @param urlLink  oss的路径地址
+     * @param pathName 本地文件(包含文件所在路径以及文件名称)
+     */
+    private void downloadSingleFileFromGrpc(String urlLink, String pathName) {
+        BufferedOutputStream bufferedOutput = null;
+        FileOutputStream outputStream = null;
+        File file = null;
+        try {
+            FileUtil.createFoldersIfNotExit(pathName);
+            byte[] fileBytes = fileSrv.readFile(urlLink);
+            //打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。
+            file = new File(pathName);
+            outputStream = new FileOutputStream(file);
+            bufferedOutput = new BufferedOutputStream(outputStream);
+            bufferedOutput.write(fileBytes);
+            outputStream.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            if (bufferedOutput != null) {
+                try {
+                    bufferedOutput.close();
+                } catch (IOException e1) {
+                    e1.printStackTrace();
+                }
+            }
+            if (outputStream != null) {
+                try {
+                    outputStream.close();
+                } catch (IOException e1) {
+                    e1.printStackTrace();
+                }
+            }
+        }
+    }
 }

+ 50 - 3
src/main/java/com/ywt/mg/web/common/FileSrv.java

@@ -1,6 +1,7 @@
 package com.ywt.mg.web.common;
 
 import com.google.protobuf.ByteString;
+import com.ywt.gapi.ResultCode;
 import com.ywt.gapi.base.file.*;
 import com.ywt.gapi.user.DoctorInfo;
 import com.ywt.gapi.user.DoctorServiceGrpc;
@@ -12,10 +13,8 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
+import java.io.*;
 import java.io.File;
-import java.io.OutputStream;
 import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.List;
@@ -124,4 +123,52 @@ public class FileSrv {
         return null;
     }
 
+
+    /**
+     * 上传本地文件到oss
+     *
+     * @param localPath 本地文件
+     * @param filename  文件名
+     * @param ossPath   oss文件路径
+     * @return 文件路径
+     */
+    public DataResponse localFileUploadToOss(String localPath, String filename, String ossPath) {
+        DataResponse response = new DataResponse();
+        try {
+            File file = new File(localPath+filename);
+            if (!file.exists()) {
+                response.parameterErrorFailed("文件不存在");
+                return response;
+            }
+            FileInputStream fis = new FileInputStream(file);
+            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            byte[] b = new byte[1024];
+            int n;
+            while ((n = fis.read(b)) != -1) {
+                bos.write(b, 0, n);
+            }
+            fis.close();
+            byte[] data = bos.toByteArray();
+            bos.close();
+
+
+            UploadFileRequest rest = UploadFileRequest.newBuilder()
+                    .setFilename(filename)
+                    .setVpath(ossPath)
+                    .setDatas(ByteString.copyFrom(data))
+                    .build();
+            UploadFileResponse resp = fileServiceBlockingStub.uploadFile(rest);
+            if (resp.getCode() == ResultCode.SUCCEED_VALUE) {
+                response.setData(resp.getFileUrl());
+            }
+            response.succeed();
+        } catch (Exception e) {
+            logger.error("FileSrv#localFileUploadToOss方法出错", e.getMessage(), e);
+            e.printStackTrace();
+            response.appExceptionFailed();
+        }
+        return response;
+    }
+
+
 }

+ 7 - 0
src/main/java/com/ywt/mg/web/controllers/enterprise/MarketApplyController.java

@@ -34,4 +34,11 @@ public class MarketApplyController {
     }
 
 
+    @ApiOperation(value = "生成pdf")
+    @RequestMapping({"/createPDF"})
+    @MGRight(menuCode = {"/createPDF"}, type = MGRightTypeDef.Menu | MGRightTypeDef.Logined)
+    void createPDF(@RequestBody BatchDownloadFilesRequest request) {
+        applyProjectService.createPDF(request);
+    }
+
 }