523096025 2 سال پیش
والد
کامیت
7c6003a15a

+ 316 - 0
admin/src/main/java/com/huimv/farm/damsubsidy/common/utils/PdfUtil.java

@@ -0,0 +1,316 @@
+package com.huimv.farm.damsubsidy.common.utils;
+
+//import cn.bt.common.utils.StringUtils;
+//import cn.bt.modules.process.instance.enums.InstanceStatusEnum;
+//import com.itextpdf.text.*;
+//import com.itextpdf.text.pdf.*;
+
+import cn.hutool.core.io.IoUtil;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+
+/**
+ * @Author: xp
+ * @Date: 2021/7/14
+ */
+public class PdfUtil {
+
+    /**
+     * 返回PDF流
+     *
+     * @param response 相应设置
+     * @param pathName 水印文件路径和名称
+     * @throws Exception 异常
+     */
+    /*public static void returnPdfStream(HttpServletResponse response, String pathName) throws Exception {
+        response.setContentType("application/pdf");
+
+        File file = new File(pathName);
+        if (file.exists()) {
+            FileInputStream in = new FileInputStream(file);
+            OutputStream out = response.getOutputStream();
+            byte[] b = new byte[1024 * 4];
+            int n;
+            while ((n = in.read(b)) > -1) {
+                out.write(b, 0, n);
+            }
+            out.flush();
+            in.close();
+            out.close();
+        }
+    }*/
+    public static void returnPdfStream2(HttpServletResponse response, String pathName, String subsidyNane) throws Exception {
+        try {
+            File file = new File(pathName );
+            InputStream in = new BufferedInputStream(new FileInputStream(file));
+            String filename = new String((subsidyNane+".pdf").getBytes(), "ISO8859_1");
+            response.setContentType("application/binary;charset=ISO8859_1");
+            response.setHeader("Content-disposition", "attachment; filename=" + filename);// 组装附件名称和格式
+            IoUtil.copy(in, response.getOutputStream());
+        } catch (Exception e) {
+            System.out.println(e);
+        }
+    }
+
+    /**
+     * 返回水印图片路径
+     *
+     * @param instanceStatus 流程状态
+     * @return 水印图片路径
+     */
+//    public static String returnWatermarkPath(int instanceStatus) {
+//        String watermarkPath = "ioffice-api/src/main/resources/static/watermark";
+//        if (InstanceStatusEnum.E_0.getCode().equals(instanceStatus)) {
+//            watermarkPath = watermarkPath + "/已作废.png";
+//
+//        } else if (InstanceStatusEnum.E_2.getCode().equals(instanceStatus)) {
+//            watermarkPath = watermarkPath + "/审批通过.png";
+//
+//        } else {
+//            watermarkPath = watermarkPath + "/审批中.png";
+//        }
+//        return watermarkPath;
+//    }
+//
+//    /**
+//     * 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
+//     *
+//     * @param pdfPath     保存路径
+//     * @param document    文档
+//     * @param pdfPathName 文件保存路径和名称
+//     * @return 书写器(Writer)
+//     * @throws Exception
+//     */
+//    public static PdfWriter createPdfWriter(String pdfPath, Document document, String pdfPathName) throws Exception {
+//
+//        //判断文件夹是否存在
+//        File file = new File(pdfPath);
+//        if (!file.exists()) {
+//            file.mkdir();
+//        }
+//        file = new File(pdfPathName);
+//
+//        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
+//        writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);
+//
+//        return writer;
+//    }
+//
+//    /**
+//     * 设置第一标题内容
+//     *
+//     * @param title    第一标题
+//     * @param document 文档
+//     * @throws Exception 异常
+//     */
+//    public static void setPdfFirstTitle(String title, Document document) throws Exception {
+//        Paragraph paragraph = new Paragraph(title, getPdfChineseFont(0));
+//        paragraph.setAlignment(Element.ALIGN_CENTER);
+//        paragraph.setSpacingAfter(2);
+//        document.add(paragraph);
+//    }
+//
+//    /**
+//     * 设置第二标题内容
+//     *
+//     * @param title           第二标题
+//     * @param document        文档
+//     * @param alignment       对齐方式
+//     * @param firstLineIndent 第一行缩进
+//     * @param spacingAfter    之后间隔
+//     * @throws Exception
+//     */
+//    public static void setPdfSecondTitle(String title, Document document, int alignment, int firstLineIndent, int spacingAfter) throws Exception {
+//        Paragraph lsh = new Paragraph(title, getPdfChineseFont(1));
+//        lsh.setAlignment(alignment);
+//        lsh.setFirstLineIndent(firstLineIndent);
+//        lsh.setSpacingAfter(spacingAfter);
+//        document.add(lsh);
+//    }
+//
+//    /**
+//     * 设置表格内容 并将表格加入文档中
+//     *
+//     * @param dates    数据
+//     * @param document 文档
+//     * @param table    表格
+//     * @throws Exception 异常
+//     */
+//    public static void setPdfTableContent(Object[][] dates, Document document, PdfPTable table) throws Exception {
+//        for (int i = 0; i < dates.length; i++) {
+//            for (int j = 0; j < dates[i].length; j++) {
+//                //表格的单元格
+//                PdfPCell pdfCell = new PdfPCell();
+//                //设置表格行高
+//                if (i > 0 && i < 3) {
+//                    pdfCell.setMinimumHeight(50);
+//                } else {
+//                    pdfCell.setMinimumHeight(25);
+//                }
+//                Paragraph paragraph = new Paragraph(dates[i][j] + "", getPdfChineseFont(1));
+//                pdfCell.setPhrase(paragraph);
+//
+//                setCellStyle(pdfCell);
+//                table.addCell(pdfCell);
+//            }
+//        }
+//
+//        document.add(table);
+//    }
+//
+//    /**
+//     * 设置水印
+//     *
+//     * @param inputFile 要这设置水印的文件路径
+//     * @param imageFile 水印图片路径
+//     * @param tag       标记
+//     * @return 生成水印文件的路径
+//     */
+//    public static String imageWaterMark(String inputFile, String imageFile, String tag) throws Exception {
+//        String[] spe = separatePath(inputFile);
+//        String outputFile = spe[0] + tag + "." + spe[1];
+//
+//        PdfReader reader = new PdfReader(inputFile);
+//        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
+//
+//        int total = reader.getNumberOfPages() + 1;
+//
+//        Image image = Image.getInstance(imageFile);
+//        //坐标
+//        image.setAbsolutePosition(389, 730);
+//        //自定义大小
+//        image.scaleAbsolute(80, 80);
+//        //旋转 弧度
+//        image.setRotation(-55);
+//
+//        //旋转 角度
+//        image.setRotationDegrees(0);
+//        //依照比例缩放
+//        image.scalePercent(50);
+//
+//        PdfGState gs = new PdfGState();
+//        // 设置透明度为0.2
+//        gs.setFillOpacity(0.2f);
+//
+//
+//        PdfContentByte under;
+//        //给每一页加水印
+//        for (int i = 1; i < total; i++) {
+//            under = stamper.getUnderContent(i);
+//            under.beginText();
+//            // 添加水印图片
+//            under.addImage(image);
+//            under.setGState(gs);
+//        }
+//        stamper.close();
+//        reader.close();
+//        return outputFile;
+//    }
+//
+//    /**
+//     * 拆分原文件路径
+//     *
+//     * @param path 原文件路径
+//     * @return 拆分原路径的数组
+//     */
+//    public static String[] separatePath(String path) {
+//        if (StringUtils.isBlank(path)) {
+//            return null;
+//        }
+//        String[] sep = path.split("\\.");
+//        return new String[]{sep[0], sep[1]};
+//    }
+//
+//    /**
+//     * 设置表格单元格样式
+//     *
+//     * @param pdfCell 单元格对象
+//     */
+//    public static void setCellStyle(PdfPCell pdfCell) {
+//        pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
+//        pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
+//        pdfCell.setBackgroundColor(new BaseColor(0xdd7e6b));
+//        pdfCell.setBorderWidthTop(0.1f);
+//        pdfCell.setBorderWidthBottom(0.1f);
+//        pdfCell.setBorderWidthLeft(0.1f);
+//        pdfCell.setBorderWidthRight(0.1f);
+//    }
+//
+//    /**
+//     * 设置pdf字体及大小
+//     *
+//     * @param type 标题或者内容 0-内容 1-标题
+//     * @return 字体
+//     * @throws Exception 异常
+//     */
+//    public static Font getPdfChineseFont(int type) throws Exception {
+//        // 使用系统字体
+//        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
+//        Font font;
+//        if (type == 1) {
+//            font = new Font(bfChinese);
+//        } else {
+//            font = new Font(bfChinese, 18, Font.BOLD);
+//        }
+//
+//        return font;
+//    }
+//
+//    /**
+//     * 删除文件夹
+//     *
+//     * @param folderPath 文件路基
+//     */
+//    public static void delFolder(String folderPath) {
+//        // 删除完里面所有内容
+//        delAllFile(folderPath);
+//        String filePath = folderPath;
+//        filePath = filePath.toString();
+//        java.io.File myFilePath = new java.io.File(filePath);
+//        // 删除空文件夹
+//        myFilePath.delete();
+//    }
+//
+//    /**
+//     * 删除指定文件夹下所有文件
+//     *
+//     * @param path 文件路基
+//     * @return 是否成功
+//     */
+//    public static boolean delAllFile(String path) {
+//        boolean flag = false;
+//        File file = new File(path);
+//        String[] tempList = file.list();
+//        File temp = null;
+//        for (int i = 0; i < tempList.length; i++) {
+//            if (path.endsWith(File.separator)) {
+//                temp = new File(path + tempList[i]);
+//            } else {
+//                temp = new File(path + File.separator + tempList[i]);
+//            }
+//            if (temp.isFile()) {
+//                temp.delete();
+//            }
+//            if (temp.isDirectory()) {
+//                // 先删除文件夹里面的文件
+//                delAllFile(path + "/" + tempList[i]);
+//                // 再删除空文件夹
+//                delFolder(path + "/" + tempList[i]);
+//                flag = true;
+//            }
+//        }
+//        return flag;
+//    }
+//    public static boolean delAllFile(String path) {
+//        boolean flag = false;
+//        File file = new File(path);
+//        File temp = null;
+//
+//            if (temp.isFile()) {
+//                temp.delete();
+//            }
+//        return flag;
+//    }
+}
+

+ 5 - 1
admin/src/main/java/com/huimv/farm/damsubsidy/config/InterceptorConfig.java

@@ -1,3 +1,4 @@
+/*
 package com.huimv.farm.damsubsidy.config;
 
 import org.springframework.context.annotation.Bean;
@@ -5,12 +6,14 @@ import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
+*/
 /**
  * @Description: 注册验证tocken的拦截器
  * @Author
  * @Date 2021/4/19 20:41
  * @Version V1.0
- */
+ *//*
+
 @Configuration
 public class InterceptorConfig implements WebMvcConfigurer {
     @Bean
@@ -24,3 +27,4 @@ public class InterceptorConfig implements WebMvcConfigurer {
                 excludePathPatterns("/sys-user/*");
     }
 }
+*/

+ 82 - 82
admin/src/main/java/com/huimv/farm/damsubsidy/config/JWTInterceptor.java

@@ -1,82 +1,82 @@
-package com.huimv.farm.damsubsidy.config;
-
-import com.alibaba.fastjson.JSONObject;
-import com.huimv.farm.damsubsidy.common.token.TokenConstant;
-import com.huimv.farm.damsubsidy.common.token.TokenSign;
-import io.jsonwebtoken.Claims;
-import org.springframework.web.method.HandlerMethod;
-import org.springframework.web.servlet.HandlerInterceptor;
-import org.springframework.web.servlet.ModelAndView;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * <p>
- * jwt拦截器
- * </p>
- *
- * @since 2021/4/19
- */
-public class JWTInterceptor implements HandlerInterceptor {
-
-
-    @Override
-    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
-        // 如果不是映射到方法,则直接通过
-        if (!(handler instanceof HandlerMethod)) {
-            return true;
-        }
-
-        response.setContentType("application/json;charset=utf-8");
-        // 获取token
-        String token = request.getHeader("accessToken");
-
-
-        if (null == token) {
-            Map<String, Object> map = new HashMap<>();
-            map.put("data", "token is null");
-            map.put("code", "401");
-            response.setStatus(401);
-            response.getWriter().write(JSONObject.toJSONString(map));
-            return false;
-        } else {
-            Claims claims = TokenSign.getClaims(token);
-            if (claims == null) {
-                Map<String, Object> map = new HashMap<>();
-                map.put("data", "token is overdue");
-                map.put("code", "403");
-                response.setStatus(403);
-                response.getWriter().write(JSONObject.toJSONString(map));
-                return false;
-            }
-
-            boolean result = TokenSign.verify(token);
-            if (result) {
-                //更新存储的token信息
-                TokenConstant.updateTokenMap(token);
-                return true;
-            }
-            Map<String, Object> map = new HashMap<>();
-            map.put("data", "token is null");
-            map.put("code", "401");
-            response.setStatus(401);
-            response.getWriter().write(JSONObject.toJSONString(map));
-            return false;
-
-        }
-    }
-
-
-    @Override
-    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
-
-    }
-
-    @Override
-    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
-
-    }
-}
+//package com.huimv.farm.damsubsidy.config;
+//
+//import com.alibaba.fastjson.JSONObject;
+//import com.huimv.farm.damsubsidy.common.token.TokenConstant;
+//import com.huimv.farm.damsubsidy.common.token.TokenSign;
+//import io.jsonwebtoken.Claims;
+//import org.springframework.web.method.HandlerMethod;
+//import org.springframework.web.servlet.HandlerInterceptor;
+//import org.springframework.web.servlet.ModelAndView;
+//
+//import javax.servlet.http.HttpServletRequest;
+//import javax.servlet.http.HttpServletResponse;
+//import java.util.HashMap;
+//import java.util.Map;
+//
+///**
+// * <p>
+// * jwt拦截器
+// * </p>
+// *
+// * @since 2021/4/19
+// */
+//public class JWTInterceptor implements HandlerInterceptor {
+//
+//
+//    @Override
+//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
+//        // 如果不是映射到方法,则直接通过
+//        if (!(handler instanceof HandlerMethod)) {
+//            return true;
+//        }
+//
+//        response.setContentType("application/json;charset=utf-8");
+//        // 获取token
+//        String token = request.getHeader("accessToken");
+//
+//
+//        if (null == token) {
+//            Map<String, Object> map = new HashMap<>();
+//            map.put("data", "token is null");
+//            map.put("code", "401");
+//            response.setStatus(401);
+//            response.getWriter().write(JSONObject.toJSONString(map));
+//            return false;
+//        } else {
+//            Claims claims = TokenSign.getClaims(token);
+//            if (claims == null) {
+//                Map<String, Object> map = new HashMap<>();
+//                map.put("data", "token is overdue");
+//                map.put("code", "403");
+//                response.setStatus(403);
+//                response.getWriter().write(JSONObject.toJSONString(map));
+//                return false;
+//            }
+//
+//            boolean result = TokenSign.verify(token);
+//            if (result) {
+//                //更新存储的token信息
+//                TokenConstant.updateTokenMap(token);
+//                return true;
+//            }
+//            Map<String, Object> map = new HashMap<>();
+//            map.put("data", "token is null");
+//            map.put("code", "401");
+//            response.setStatus(401);
+//            response.getWriter().write(JSONObject.toJSONString(map));
+//            return false;
+//
+//        }
+//    }
+//
+//
+//    @Override
+//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
+//
+//    }
+//
+//    @Override
+//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
+//
+//    }
+//}

+ 11 - 11
admin/src/main/java/com/huimv/farm/damsubsidy/controller/BillSubsidyController.java

@@ -1,15 +1,13 @@
 package com.huimv.farm.damsubsidy.controller;
 
 
-import cn.hutool.core.date.DateTime;
 import cn.hutool.core.date.DateUtil;
 import cn.hutool.core.lang.UUID;
-import com.huimv.farm.damsubsidy.common.token.TokenSign;
 import com.huimv.farm.damsubsidy.common.utils.Result;
-import com.huimv.farm.damsubsidy.common.utils.ResultCode;
 import com.huimv.farm.damsubsidy.common.utils.UploadImage;
 import com.huimv.farm.damsubsidy.entity.BillSubsidy;
 import com.huimv.farm.damsubsidy.service.IBillSubsidyService;
+import com.huimv.farm.damsubsidy.common.utils.PdfUtil;
 import com.huimv.farm.test.Print;
 import com.spire.xls.FileFormat;
 import com.spire.xls.Workbook;
@@ -19,9 +17,8 @@ import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.http.HttpServletRequest;
-import java.io.BufferedInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
@@ -136,9 +133,9 @@ public class BillSubsidyController {
     }
 
     //打印
-    @PostMapping("/print")
-    public Result print(HttpServletRequest httpServletRequest, @RequestBody Map<String, String> parasMap) throws Exception {
-        Integer id=Integer.parseInt(parasMap.get("id"));
+    @GetMapping("/print")
+    public void print(HttpServletResponse response, HttpServletRequest httpServletRequest,@RequestParam(name = "id", required = true) Integer id) throws Exception {
+//        Integer id=Integer.parseInt(parasMap.get("id"));
         BillSubsidy subsidy = subsidyService.getById(id);
         Print print = new Print();
         String path = print.print(subsidy);
@@ -148,7 +145,10 @@ public class BillSubsidyController {
         wb.loadFromFile(path);
 
         //调用方法保存为PDF格式
-        wb.saveToFile("I://"+subsidy.getFarmerName()+".pdf", FileFormat.PDF);
-        return new Result(ResultCode.SUCCESS,"I://"+subsidy.getFarmerName()+".pdf");
+       String pdfPath =   "G://"+subsidy.getFarmerName()+".pdf";
+        wb.saveToFile(pdfPath, FileFormat.PDF);
+        PdfUtil.returnPdfStream2(response,pdfPath,subsidy.getFarmerName());
+        //文件删除 TODO
+
     }
 }

+ 4 - 4
admin/src/main/java/com/huimv/farm/test/Print.java

@@ -21,14 +21,14 @@ public class Print {
      */
     public  String print(BillSubsidy subsidy) throws Exception {
         //准备数据
-
+        String path ="G://order_contract.xls";
         //获取模板文件,你自己当前模板的位置  我这里为当前项目下
         //如果为系统路径 为: InputStream is = new FileInputStream("F://student.xlsx");
-        InputStream is = new FileInputStream("I://order_contract.xlsx");
+        InputStream is = new FileInputStream("G://order_contract.xlsx");
 //        InputStream is = Print.class.getClassLoader().getResourceAsStream("student.xlsx");
 //        InputStream is = Print.class.getClassLoader().getResourceAsStream("order_contract.xls");
         //根据模板生成的文件保存路径  我这里保存在本地D盘
-        OutputStream os = new FileOutputStream("I://order_contract.xls");
+        OutputStream os = new FileOutputStream(path);
         //绑定数据
         Context context = new Context();
         //涉及太多只写了一个单独的
@@ -51,7 +51,7 @@ public class Print {
         context.putVar("userNum", subsidy.getBankCardId());
         //生成
         JxlsHelper.getInstance().processTemplate(is, os, context);
-        String path = String.valueOf(os);
+//        String path = String.valueOf(os);
         return path;
     }