wangliang %!s(int64=4) %!d(string=hai) anos
pai
achega
574dac688e

+ 47 - 0
distributed-print-business/src/main/java/com/qmth/distributed/print/business/bean/dto/PdfDto.java

@@ -0,0 +1,47 @@
+package com.qmth.distributed.print.business.bean.dto;
+
+import com.qmth.distributed.print.business.enums.PageSizeEnum;
+import io.swagger.annotations.ApiModelProperty;
+
+/**
+ * @Description: pdf dto
+ * @Param:
+ * @return:
+ * @Author: wangliang
+ * @Date: 2021/4/13
+ */
+public class PdfDto {
+
+    @ApiModelProperty(name = "路径")
+    String path;
+
+    @ApiModelProperty(name = "页数")
+    Integer pageCount;
+
+    @ApiModelProperty(name = "页面大小")
+    PageSizeEnum pageSize;
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+
+    public Integer getPageCount() {
+        return pageCount;
+    }
+
+    public void setPageCount(Integer pageCount) {
+        this.pageCount = pageCount;
+    }
+
+    public PageSizeEnum getPageSize() {
+        return pageSize;
+    }
+
+    public void setPageSize(PageSizeEnum pageSize) {
+        this.pageSize = pageSize;
+    }
+}

+ 2 - 1
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/BasicAttachmentService.java

@@ -1,6 +1,7 @@
 package com.qmth.distributed.print.business.service;
 
 import com.baomidou.mybatisplus.extension.service.IService;
+import com.itextpdf.text.DocumentException;
 import com.qmth.distributed.print.business.entity.BasicAttachment;
 import com.qmth.distributed.print.business.enums.UploadFileEnum;
 import org.springframework.web.multipart.MultipartFile;
@@ -70,7 +71,7 @@ public interface BasicAttachmentService extends IService<BasicAttachment> {
      * @return
      * @throws IOException
      */
-    public BasicAttachment saveAttachmentPdf(BasicAttachment basicAttachment, List<String> pdfList, Integer printCount) throws IOException;
+    public BasicAttachment saveAttachmentPdf(BasicAttachment basicAttachment, List<String> pdfList, Integer printCount) throws IOException, DocumentException;
 
     /**
      * 删除附件

+ 77 - 46
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/impl/BasicAttachmentServiceImpl.java

@@ -3,7 +3,9 @@ package com.qmth.distributed.print.business.service.impl;
 import com.alibaba.fastjson.JSONObject;
 import com.aliyun.oss.common.utils.BinaryUtil;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.itextpdf.text.DocumentException;
 import com.itextpdf.text.pdf.PdfReader;
+import com.itextpdf.text.pdf.PdfStamper;
 import com.qmth.boot.api.exception.ApiException;
 import com.qmth.distributed.print.business.config.DictionaryConfig;
 import com.qmth.distributed.print.business.entity.BasicAttachment;
@@ -14,6 +16,7 @@ import com.qmth.distributed.print.business.mapper.BasicAttachmentMapper;
 import com.qmth.distributed.print.business.service.BasicAttachmentService;
 import com.qmth.distributed.print.business.util.HtmlToPdfUtil;
 import com.qmth.distributed.print.business.util.OssUtil;
+import com.qmth.distributed.print.business.util.PdfUtil;
 import com.qmth.distributed.print.business.util.ServletUtil;
 import com.qmth.distributed.print.common.contant.SystemConstant;
 import com.qmth.distributed.print.common.enums.ExceptionResultEnum;
@@ -21,6 +24,7 @@ import com.qmth.distributed.print.common.util.HexUtils;
 import com.qmth.distributed.print.common.util.ResultUtil;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -30,9 +34,7 @@ import org.springframework.util.FileCopyUtils;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
+import java.io.*;
 import java.math.BigDecimal;
 import java.time.LocalDateTime;
 import java.util.List;
@@ -216,56 +218,85 @@ public class BasicAttachmentServiceImpl extends ServiceImpl<BasicAttachmentMappe
      */
     @Override
     @Transactional
-    public BasicAttachment saveAttachmentPdf(BasicAttachment basicAttachment, List<String> pdfList, Integer printCount) throws IOException {
-        boolean oss = dictionaryConfig.sysDomain().isOss();
-        JSONObject jsonObject = JSONObject.parseObject(basicAttachment.getPath());
-        String type = basicAttachment.getType();
-        String filePath = null;
-        String url = null;
-        File htmlFile = null;
-        if (Objects.nonNull(type) && Objects.equals(type, SystemConstant.FTL_PREFIX)) {
-            filePath = (String) jsonObject.get(SystemConstant.HTML_PATH);
-            url = SystemConstant.TEMP_FILES_DIR + File.separator + filePath;
-            htmlFile = new File(url);
-        } else if (Objects.nonNull(type) && Objects.equals(type, SystemConstant.HTML_PREFIX)) {
-            filePath = (String) jsonObject.get(SystemConstant.PATH);
-            url = SystemConstant.TEMP_FILES_DIR + File.separator + filePath;
-            htmlFile = ossUtil.ossDownload(filePath, url);
-        }
-        String pdfDirName = filePath.replaceAll(SystemConstant.HTML_PREFIX, SystemConstant.PDF_PREFIX).replaceAll(UploadFileEnum.HTML.name().toLowerCase(), UploadFileEnum.PDF.name().toLowerCase());
-        String destUrl = SystemConstant.PDF_TEMP_FILES_DIR + File.separator + pdfDirName;
-        HtmlToPdfUtil.convert(htmlFile.getPath(), destUrl, PageSizeEnum.A4);
-        File pdfFile = new File(destUrl);
-        if (!pdfFile.getParentFile().exists()) {
-            pdfFile.getParentFile().mkdirs();
-            pdfFile.createNewFile();
-        }
-        String fileMd5 = DigestUtils.md5Hex(new FileInputStream(pdfFile));
-        if (oss) {//上传至oss
-            ossUtil.ossUpload(pdfDirName, pdfFile, BinaryUtil.toBase64String(HexUtils.decodeHex(fileMd5)));
-            jsonObject.put(SystemConstant.PDF_PATH, pdfDirName);
+    public BasicAttachment saveAttachmentPdf(BasicAttachment basicAttachment, List<String> pdfList, Integer printCount) throws IOException, DocumentException {
+        try {
+            boolean oss = dictionaryConfig.sysDomain().isOss();
+            JSONObject jsonObject = JSONObject.parseObject(basicAttachment.getPath());
+            String type = basicAttachment.getType();
+            String filePath = null;
+            String url = null;
+            File htmlFile = null;
             if (Objects.nonNull(type) && Objects.equals(type, SystemConstant.FTL_PREFIX)) {
-                jsonObject.put(SystemConstant.UPLOAD_TYPE, new UploadFileEnum[]{
-                        UploadFileEnum.FILE,
-                        UploadFileEnum.HTML,
-                        UploadFileEnum.PDF
-                });
+                filePath = (String) jsonObject.get(SystemConstant.HTML_PATH);
+                url = SystemConstant.TEMP_FILES_DIR + File.separator + filePath;
+                htmlFile = new File(url);
+            } else if (Objects.nonNull(type) && Objects.equals(type, SystemConstant.HTML_PREFIX)) {
+                filePath = (String) jsonObject.get(SystemConstant.PATH);
+                url = SystemConstant.TEMP_FILES_DIR + File.separator + filePath;
+                htmlFile = ossUtil.ossDownload(filePath, url);
+            }
+            String pdfDirName = filePath.replaceAll(SystemConstant.HTML_PREFIX, SystemConstant.PDF_PREFIX).replaceAll(UploadFileEnum.HTML.name().toLowerCase(), UploadFileEnum.PDF.name().toLowerCase());
+            String destUrl = SystemConstant.PDF_TEMP_FILES_DIR + File.separator + pdfDirName;
+            HtmlToPdfUtil.convert(htmlFile.getPath(), destUrl, PageSizeEnum.A4);
+            File pdfFile = new File(destUrl);
+            if (!pdfFile.getParentFile().exists()) {
+                pdfFile.getParentFile().mkdirs();
+                pdfFile.createNewFile();
+            }
+            String fileMd5 = DigestUtils.md5Hex(new FileInputStream(pdfFile));
+            if (oss) {//上传至oss
+                int pageCount = PdfUtil.addPdfPage(pdfFile);
+
+                ossUtil.ossUpload(pdfDirName, pdfFile, BinaryUtil.toBase64String(HexUtils.decodeHex(fileMd5)));
+                jsonObject.put(SystemConstant.PDF_PATH, pdfDirName);
+                if (Objects.nonNull(type) && Objects.equals(type, SystemConstant.FTL_PREFIX)) {
+                    jsonObject.put(SystemConstant.UPLOAD_TYPE, new UploadFileEnum[]{
+                            UploadFileEnum.FILE,
+                            UploadFileEnum.HTML,
+                            UploadFileEnum.PDF
+                    });
+                } else {
+                    jsonObject.put(SystemConstant.UPLOAD_TYPE, new UploadFileEnum[]{
+                            UploadFileEnum.FILE,
+                            UploadFileEnum.PDF
+                    });
+                    htmlFile.delete();
+                }
+            }
+            basicAttachment.setPath(jsonObject.toJSONString());
+            for (int i = 0; i < printCount; i++) {
+                pdfList.add(pdfFile.getPath());
+            }
+            this.updateById(basicAttachment);
+        } catch (Exception e) {
+            log.error("请求出错", e);
+            if (e instanceof ApiException) {
+                ResultUtil.error((ApiException) e, e.getMessage());
             } else {
-                jsonObject.put(SystemConstant.UPLOAD_TYPE, new UploadFileEnum[]{
-                        UploadFileEnum.FILE,
-                        UploadFileEnum.PDF
-                });
-                htmlFile.delete();
+                ResultUtil.error(e.getMessage());
             }
         }
-        basicAttachment.setPath(jsonObject.toJSONString());
-        for (int i = 0; i < printCount; i++) {
-            pdfList.add(pdfFile.getPath());
-        }
-        this.updateById(basicAttachment);
         return basicAttachment;
     }
 
+    public static void main(String[] args) throws IOException, DocumentException {
+        File file = new File("/Users/king/Downloads/669ad9917f814bcabdd35201073885be.pdf");
+        PdfReader reader = new PdfReader(file.getPath());
+        int pageCount = reader.getNumberOfPages();
+        System.out.println("pageCount:" + pageCount);
+//
+        if (Math.abs(pageCount % 2) == 1) {//取偶
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            PdfStamper stamper = new PdfStamper(reader, baos);
+            stamper.insertPage(pageCount + 1, reader.getPageSizeWithRotation(1));
+            stamper.close();
+            FileOutputStream fileOutputStream = new FileOutputStream(file);
+            IOUtils.write(baos.toByteArray(), fileOutputStream);
+        }
+        pageCount = reader.getNumberOfPages();
+        System.out.println("pageCount:" + pageCount);
+    }
+
     /**
      * 删除附件
      *

+ 3 - 2
distributed-print-business/src/main/java/com/qmth/distributed/print/business/templete/service/impl/TaskLogicServiceImpl.java

@@ -7,6 +7,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.aliyun.oss.common.utils.BinaryUtil;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.google.gson.Gson;
+import com.itextpdf.text.DocumentException;
 import com.qmth.boot.api.exception.ApiException;
 import com.qmth.distributed.print.business.bean.dto.ExamStudentDto;
 import com.qmth.distributed.print.business.bean.dto.FieldsDto;
@@ -562,7 +563,7 @@ public class TaskLogicServiceImpl implements TaskLogicService {
      * @param ordinaryPdfList
      * @param printCount
      */
-    private void createCheckIn(BasicAttachment basicAttachment, List<String> ordinaryPdfList, Integer printCount) throws IOException {
+    private void createCheckIn(BasicAttachment basicAttachment, List<String> ordinaryPdfList, Integer printCount) throws IOException, DocumentException {
         String type = basicAttachment.getType();
         JSONObject jsonObject = JSONObject.parseObject(basicAttachment.getPath());
         if (Objects.nonNull(type) && Objects.equals(type, SystemConstant.PDF_PREFIX)) {
@@ -826,7 +827,7 @@ public class TaskLogicServiceImpl implements TaskLogicService {
         examDetail.setPagesA4(pageA4Count);
         examDetail.setStatus(ExamDetailStatusEnum.READY);
         detailService.saveOrUpdate(examDetail);
-        ossUtil.ossUpload(dirName, localPdfFile, BinaryUtil.toBase64String(HexUtils.decodeHex(DigestUtils.md5Hex(new FileInputStream(localPdfFile)))));
+        ossUtil.ossUpload(dirName, localPdfFile, DigestUtils.md5Hex(new FileInputStream(localPdfFile)));
         localPdfFile.delete();
         for (String s : mergePdfList) {
             new File(s).delete();

+ 24 - 26
distributed-print-business/src/main/java/com/qmth/distributed/print/business/util/PdfUtil.java

@@ -4,16 +4,18 @@ import com.itextpdf.text.Document;
 import com.itextpdf.text.pdf.PdfCopy;
 import com.itextpdf.text.pdf.PdfImportedPage;
 import com.itextpdf.text.pdf.PdfReader;
+import com.itextpdf.text.pdf.PdfStamper;
 import com.qmth.distributed.print.business.enums.UploadFileEnum;
 import com.qmth.distributed.print.common.contant.SystemConstant;
+import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileOutputStream;
-import java.io.InputStream;
+import java.io.IOException;
 import java.time.LocalDateTime;
-import java.util.List;
 import java.util.Objects;
 import java.util.StringJoiner;
 
@@ -80,42 +82,38 @@ public class PdfUtil {
     }
 
     /**
-     * 将多个PDF合并成一个PDF
+     * 新增pdf page
      *
-     * @param files
-     * @param outputPath
+     * @param pdfFile
+     * @return
+     * @throws IOException
      */
-    public static void mergePdf(List<InputStream> files, String outputPath) {
-        Document document = null;
-        PdfCopy copy = null;
+    public static int addPdfPage(File pdfFile) throws IOException {
         PdfReader reader = null;
+        FileOutputStream fileOutputStream = null;
         try {
-            document = new Document(new PdfReader(files.get(0)).getPageSize(1));
-            copy = new PdfCopy(document, new FileOutputStream(outputPath));
-            document.open();
-            for (int i = 0; i < files.size(); i++) {
-                reader = new PdfReader(files.get(i));
-                int numberOfPages = reader.getNumberOfPages();
-                for (int j = 1; j <= numberOfPages; j++) {
-                    document.newPage();
-                    PdfImportedPage page = copy.getImportedPage(reader, j);
-                    copy.addPage(page);
-                }
+            reader = new PdfReader(pdfFile.getPath());
+            int pageCount = reader.getNumberOfPages();
+            if (Math.abs(pageCount % 2) == 1) {//取偶
+                ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                PdfStamper stamper = new PdfStamper(reader, baos);
+                stamper.insertPage(pageCount + 1, reader.getPageSizeWithRotation(1));
+                stamper.close();
+                fileOutputStream = new FileOutputStream(pdfFile);
+                IOUtils.write(baos.toByteArray(), fileOutputStream);
             }
         } catch (Exception e) {
-            log.error("请求出错", e);
+            e.printStackTrace();
         } finally {
-            if (Objects.nonNull(document)) {
-                document.close();
-            }
             if (Objects.nonNull(reader)) {
                 reader.close();
             }
-            if (Objects.nonNull(copy)) {
-                copy.flush();
-                copy.close();
+            if (Objects.nonNull(fileOutputStream)) {
+                fileOutputStream.flush();
+                fileOutputStream.close();
             }
         }
+        return Objects.nonNull(reader) ? reader.getNumberOfPages() : 0;
     }
 
 //    public static void main(String[] args) {