licailing 4 жил өмнө
parent
commit
9b34637245

+ 9 - 0
pom.xml

@@ -23,6 +23,10 @@
             <id>Local repository</id>
             <url>file://${basedir}/libs</url>
         </repository>
+        <repository>
+            <id>com.e-iceblue</id>
+            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
+        </repository>
     </repositories>
 
     <properties>
@@ -288,6 +292,11 @@
             <artifactId>itext</artifactId>
             <version>2.1.7</version>
         </dependency>
+        <dependency>
+            <groupId>e-iceblue</groupId>
+            <artifactId>spire.pdf.free</artifactId>
+            <version>3.9.0</version>
+        </dependency>
     </dependencies>
 
 </project>

+ 105 - 66
src/main/java/com/izouma/wenlvju/service/RateService.java

@@ -2,7 +2,6 @@ package com.izouma.wenlvju.service;
 
 import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.util.ObjectUtil;
-import cn.hutool.poi.word.WordUtil;
 import com.github.kevinsawicki.http.HttpRequest;
 import com.izouma.wenlvju.config.DateConfig;
 import com.izouma.wenlvju.domain.*;
@@ -16,6 +15,11 @@ import com.izouma.wenlvju.security.Authority;
 import com.izouma.wenlvju.service.sms.NjwlSmsService;
 import com.izouma.wenlvju.utils.JpaUtils;
 import com.izouma.wenlvju.utils.ObjUtils;
+import com.lowagie.text.Document;
+import com.lowagie.text.DocumentException;
+import com.lowagie.text.Image;
+import com.lowagie.text.PageSize;
+import com.lowagie.text.pdf.PdfWriter;
 import freemarker.template.Configuration;
 import freemarker.template.Template;
 import freemarker.template.Version;
@@ -30,6 +34,9 @@ import sun.misc.BASE64Encoder;
 import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletResponse;
 import java.io.*;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
@@ -229,81 +236,87 @@ public class RateService {
     }
 
     public String Image2Base64(String imgUrl) {
-//            URL url = null;
-        InputStream is = HttpRequest.get(imgUrl).stream();
-        ByteArrayOutputStream outStream = null;
-//            HttpURLConnection httpUrl = null;
+        BASE64Encoder encoder = new BASE64Encoder();
+        return encoder.encode(HttpRequest.get(imgUrl).bytes()).replace("\n", "\r\n").replace("\r\r\n", "\r\n");
+    }
+
+    public void imgToPdf(List<InputStream> files, Rate rate) {
+        List<String> imageUrllist = new ArrayList<>();
+
+        this.addList(imageUrllist,rate.getPrivacyPolicy());
+        this.addList(imageUrllist, rate.getBusiness());
+        this.addList(imageUrllist, rate.getCredits());
+        this.addList(imageUrllist, rate.getFire());
+        this.addList(imageUrllist, rate.getHygiene());
+        this.addList(imageUrllist, rate.getFinance());
+        this.addList(imageUrllist, rate.getProperty());
+
+        String filename = "img.pdf";
+
+        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
         try {
-//                url = new URL(imgUrl);
-//                httpUrl = (HttpURLConnection) url.openConnection();
-//                httpUrl.connect();
-//                httpUrl.getInputStream();
-//                is = httpUrl.getInputStream();
-
-            outStream = new ByteArrayOutputStream();
-            //创建一个Buffer字符串
-            byte[] buffer = new byte[1024];
-            //每次读取的字符串长度,如果为-1,代表全部读取完毕
-            int len = 0;
-            //使用一个输入流从buffer里把数据读取出来
-            while ((len = is.read(buffer)) != -1) {
-                //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
-                outStream.write(buffer, 0, len);
+            FileOutputStream os = new FileOutputStream(filename);
+            PdfWriter.getInstance(doc, os);
+
+            doc.open();
+            for (String img : imageUrllist) {
+                doc.newPage();
+                Image png1 = Image.getInstance(img);
+//                float heigth = png1.getHeight();
+                float width = png1.getWidth();
+                int percent = this.getPercent(width);
+
+                png1.setAlignment(Image.MIDDLE);
+                png1.scalePercent(percent + 3);// 表示是原来图像的比例;
+                doc.add(png1);
             }
-            // 对字节数组Base64编码
-//            return new BASE64Encoder().encode(outStream.toByteArray());
-            BASE64Encoder encoder = new BASE64Encoder();
-            return encoder.encode(outStream.toByteArray()).replace("\n", "\r\n").replace("\r\r\n", "\r\n");
-        } catch (Exception e) {
+//            b = os.toByteArray();
+
+            File file = new File(filename);
+            InputStream is = new FileInputStream(file);
+            files.add(is);
+
+        } catch (IOException | DocumentException e) {
             e.printStackTrace();
-        }  //下载
-        finally {
-            if (is != null) {
-                try {
-                    is.close();
-                } catch (IOException e) {
-                    e.printStackTrace();
-                }
-            }
-            if (outStream != null) {
-                try {
-                    outStream.close();
-                } catch (IOException e) {
-                    e.printStackTrace();
-                }
-            }
-//                if (httpUrl != null) {
-//                    httpUrl.disconnect();
-//                }
+        } finally {
+            doc.close();
         }
-        return imgUrl;
     }
 
-    public List<File> upLoad(Rate rate) {
-        List<File> files = new ArrayList<>();
-        String uri = "http://192.168.50.238:8080/word2pdf";
-        // 表格
-        String export = this.export(rate);
-        InputStream is = new ByteArrayInputStream(export.getBytes());
-        File file = new File("/Users/qiufangchao/Desktop/" + "申请表" + ".pdf");
-        HttpRequest.post(uri)
-                .accept("*/*")
-                .part("file", "审核材料.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", is)
-                .receive(file);
-        files.add(file);
-        this.downloadFile(files, rate.getPrivacyPolicy(), "法人资格");
-//        this.downloadFile(files, rate.getBusiness(), "业务内容");
-//        this.downloadFile(files, rate.getCredits(), "社会信誉");
-//        this.downloadFile(files, rate.getFire(), "消防安全");
-//        this.downloadFile(files, rate.getHygiene(), "卫生防疫");
-//        this.downloadFile(files, rate.getFinance(), "财务报表");
-//        this.downloadFile(files, rate.getProperty(), "房产证明");
-        return files;
+    public void addList(List<String> list, List<String> imgs) {
+        imgs.forEach(img -> {
+            if ("png".equalsIgnoreCase(this.getSuffix(img)) || "jpg".equalsIgnoreCase(this.getSuffix(img))
+                    || "jpeg".equalsIgnoreCase(this.getSuffix(img))) {
+                list.add(img);
+            }
+        });
+    }
+
+    /**
+     * 等比压缩,获取压缩百分比
+     *
+     * @param weight 图片的宽度
+     * @return 压缩百分比
+     */
+    public int getPercent(float weight) {
+//        float percent;
+//        if (height > weight) {
+//            percent = PageSize.A4.getHeight() / height * 100;
+//        } else {
+//            percent = PageSize.A4.getWidth() / weight * 100;
+//        }
+//        return Math.round(percent);
+        int p;
+        float p2;
+        p2 = 530 / weight * 100;
+        p = Math.round(p2);
+        return p;
     }
 
-    public List<InputStream> upLoad1(Rate rate) {
+    public List<InputStream> upLoad1(Rate rate) throws UnsupportedEncodingException {
         List<InputStream> files = new ArrayList<>();
         String uri = "http://192.168.50.238:8080/word2pdf";
+
         // 表格
         String export = this.export(rate);
         InputStream is = new ByteArrayInputStream(export.getBytes());
@@ -319,6 +332,9 @@ public class RateService {
         this.downloadFile1(files, rate.getHygiene());
         this.downloadFile1(files, rate.getFinance());
         this.downloadFile1(files, rate.getProperty());
+
+        this.imgToPdf(files, rate);
+
         return files;
     }
 
@@ -341,6 +357,28 @@ public class RateService {
         });
     }
 
+    public List<File> upLoad(Rate rate) {
+        List<File> files = new ArrayList<>();
+        String uri = "http://192.168.50.238:8080/word2pdf";
+        // 表格
+        String export = this.export(rate);
+        InputStream is = new ByteArrayInputStream(export.getBytes());
+        File file = new File("/Users/qiufangchao/Desktop/" + "申请表" + ".pdf");
+        HttpRequest.post(uri)
+                .accept("*/*")
+                .part("file", "审核材料.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", is)
+                .receive(file);
+        files.add(file);
+        this.downloadFile(files, rate.getPrivacyPolicy(), "法人资格");
+//        this.downloadFile(files, rate.getBusiness(), "业务内容");
+//        this.downloadFile(files, rate.getCredits(), "社会信誉");
+//        this.downloadFile(files, rate.getFire(), "消防安全");
+//        this.downloadFile(files, rate.getHygiene(), "卫生防疫");
+//        this.downloadFile(files, rate.getFinance(), "财务报表");
+//        this.downloadFile(files, rate.getProperty(), "房产证明");
+        return files;
+    }
+
     public void downloadFile(List<File> files, List<String> urls, String filename) {
         AtomicInteger num = new AtomicInteger(1);
         urls.forEach(privacy -> {
@@ -372,6 +410,7 @@ public class RateService {
         Rate rate = rateRepo.findById(id).orElseThrow(new BusinessException("无记录"));
         List<InputStream> files = this.upLoad1(rate);
 
+
         // pdf合并工具类
         PDFMergerUtility mergePdf = new PDFMergerUtility();
         mergePdf.addSources(files);

+ 52 - 39
src/test/java/com/izouma/wenlvju/service/RateServiceTest.java

@@ -6,12 +6,17 @@ import com.izouma.wenlvju.ApplicationTests;
 import com.izouma.wenlvju.domain.Rate;
 import com.izouma.wenlvju.exception.BusinessException;
 import com.izouma.wenlvju.repo.RateRepo;
+import com.lowagie.text.Document;
+import com.lowagie.text.DocumentException;
+import com.lowagie.text.Image;
+import com.lowagie.text.PageSize;
+import com.lowagie.text.pdf.PdfWriter;
+import com.spire.pdf.FileFormat;
 import org.apache.pdfbox.io.MemoryUsageSetting;
 import org.apache.pdfbox.multipdf.PDFMergerUtility;
 import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
 
-import java.awt.*;
 import java.io.*;
 import java.time.LocalDateTime;
 import java.util.List;
@@ -29,9 +34,9 @@ public class RateServiceTest extends ApplicationTests {
     }
 
     @Test
-    public void test2() {
+    public void test2() throws UnsupportedEncodingException {
 
-        Rate rate = rateRepo.findById(467L).orElseThrow(new BusinessException("无记录"));
+        Rate rate = rateRepo.findById(625L).orElseThrow(new BusinessException("无记录"));
         List<InputStream> files = rateService.upLoad1(rate);
 
         String targetPath = "/Users/qiufangchao/Desktop/result.pdf";
@@ -74,11 +79,6 @@ public class RateServiceTest extends ApplicationTests {
                 .part("file", "审核材料.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", is)
                 .stream();
 
-//        StringWriter writer = new StringWriter();
-//        IOUtils.copy(stream, writer, StandardCharsets.UTF_8.name());
-//        String str = writer.toString();
-//        stream.close();
-
         int index;
         byte[] bytes = new byte[1024];
         FileOutputStream downloadFile = new FileOutputStream(targetPath);
@@ -123,38 +123,51 @@ public class RateServiceTest extends ApplicationTests {
 
     @Test
     public void test8() {
-//        String TAG = "PdfManager";
-//        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
-//        try {
-//            PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
-//            doc.open();
-//            for (int i = 0; i < imageUrllist.size(); i++) {
-//                doc.newPage();
-////                doc.add(new Paragraph("简单使用iText"));
-//                Image png1 = Image.getInstance(imageUrllist.get(i));
-//                float heigth = png1.getHeight();
-//                float width = png1.getWidth();
-//                int percent = getPercent2(heigth, width);
-//                png1.setAlignment(Image.MIDDLE);
-//                png1.scalePercent(percent+3);// 表示是原来图像的比例;
-//                doc.add(png1);
-//            }
-//
-//        } catch (FileNotFoundException e) {
-//            e.printStackTrace();
-//        } catch (DocumentException e) {
-//            e.printStackTrace();
-//        } catch (IOException e) {
-//            e.printStackTrace();
-//        }finally {
-//            doc.close();
+
+//        String img = "https://ticket-exchange.oss-cn-hangzhou.aliyuncs.com/image/2021-04-29-12-39-59rzhrQYhu.jpg";
+
+        Rate rate = rateRepo.findById(625L).orElseThrow(new BusinessException("wu"));
+        List<String> imageUrllist = rate.getBusiness();
+
+        // PDF文件保存地址
+        String mOutputPdfFileName = "/Users/qiufangchao/Desktop/test1.pdf";
+
+        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
+        try {
+            PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
+            doc.open();
+            for (String img : imageUrllist) {
+                doc.newPage();
+                Image png1 = Image.getInstance(img);
+                float heigth = png1.getHeight();
+                float width = png1.getWidth();
+                int percent = rateService.getPercent(width);
+
+                png1.setAlignment(Image.MIDDLE);
+                png1.scalePercent(percent + 3);// 表示是原来图像的比例;
+                doc.add(png1);
+            }
+
+        } catch (IOException | DocumentException e) {
+            e.printStackTrace();
+        } finally {
+            doc.close();
+
+        }
+        File mOutputPdfFile = new File(mOutputPdfFileName);
+        if (!mOutputPdfFile.exists()) {
+            mOutputPdfFile.deleteOnExit();
+        }
+    }
+
+    @Test
+    public void test9() {
+//        //加载Excel文档
+//        Workbook wb = new Workbook();
+//        wb.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.xlsx");
 //
-//        }
-//        File mOutputPdfFile = new File(mOutputPdfFileName);
-//        if (!mOutputPdfFile.exists()) {
-//            mOutputPdfFile.deleteOnExit();
-//            return null;
-//        }
+//        //调用方法保存为PDF格式
+//        wb.saveToFile("output/ToPDF.pdf", FileFormat.PDF);
     }
 
 }