Przeglądaj źródła

添加Excel和Wrod转换PDF和PDF合并

anderx 4 dni temu
rodzic
commit
1de2d6ddfe

+ 17 - 0
pom.xml

@@ -476,6 +476,22 @@
 			<artifactId>commons-io</artifactId>
 			<version>2.11.0</version>
 		</dependency>
+		<!-- 引入自定义 jar 包  word.Excel转PDF -->
+		<dependency>
+			<groupId>com.aspose</groupId>
+			<artifactId>aspose-cells</artifactId>
+			<version>8.5.2</version>
+			<scope>system</scope>
+			<systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath>
+		</dependency>
+		<dependency>
+			<groupId>com.aspose</groupId>
+			<artifactId>aspose-words</artifactId>
+			<version>15.8.0</version>
+			<scope>system</scope>
+			<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0.jar</systemPath>
+		</dependency>
+
 
 
 
@@ -576,6 +592,7 @@
 
 
 
+
 	<pluginRepositories>
 		<pluginRepository>
 			<id>aliyun-plugin</id>

+ 1 - 1
src/main/java/com/goafanti/common/controller/PublicController.java

@@ -1035,7 +1035,7 @@ public class PublicController extends CertifyApiController {
 	public Result mergeDocumentsToPdf(HttpServletResponse  response) throws DocumentException, IOException {
 		// 转换Word为PDF文件
 //		PDFUtils.convertWordToPDF("E:/4.docx", "E:/4-PDF.pdf");
-		PDFUtils.newConvertWordToPDF("E:/tmp/0814.docx", "E:/tmp/0814-PDF.pdf");
+		PDFUtils.newConvertWordToPDF("F:/data/111.docx", "F:/data/0814-PDF.pdf");
 //		PDFUtils.convertXlsxToPDF("E:/tmp/0811.xlsx", "E:/tmp/0811-PDF.pdf");
 //		List<String> list = Arrays.asList(
 //				"E:/tmp/4-PDF.pdf",

+ 138 - 0
src/main/java/com/goafanti/common/utils/pdf/ExcelToPdfUtils.java

@@ -0,0 +1,138 @@
+package com.goafanti.common.utils.pdf;
+
+
+import com.aspose.cells.License;
+import com.aspose.cells.PdfSaveOptions;
+import com.aspose.cells.Workbook;
+
+import java.io.FileOutputStream;
+import java.io.InputStream;
+
+/**
+ * Excel转PDF工具类
+ *
+ */
+public class ExcelToPdfUtils {
+
+    /**
+     * excel 转 pdf
+     *
+     * @param excelFilePath excel文件路径
+     */
+    public static void excel2pdf(String excelFilePath) {
+        excel2pdf(excelFilePath, null, null);
+    }
+
+    /**
+     * excel 转 pdf
+     *
+     * @param excelFilePath excel文件路径
+     * @param convertSheets 需要转换的sheet
+     */
+    public static void excel2pdf(String excelFilePath, int[] convertSheets) {
+        excel2pdf(excelFilePath, null, convertSheets);
+    }
+
+    /**
+     * excel 转 pdf
+     *
+     * @param excelFilePath excel文件路径
+     * @param pdfFilePath   pdf文件路径
+     */
+    public static void excel2pdf(String excelFilePath, String pdfFilePath) {
+        excel2pdf(excelFilePath, pdfFilePath, null);
+    }
+
+    /**
+     * excel 转 pdf
+     *
+     * @param excelFilePath excel文件路径
+     * @param pdfFilePath   pdf文件路径
+     * @param convertSheets 需要转换的sheet
+     */
+    public static void excel2pdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
+        try {
+            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
+            // 验证 License
+            getLicense();
+            Workbook wb = new Workbook(excelFilePath);
+            FileOutputStream fileOS = new FileOutputStream(pdfFilePath);
+            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
+
+            //删除强制每个sheet为一页的设置,允许Aspose自动分页
+            pdfSaveOptions.setOnePagePerSheet(true);
+            // 如果有指定需要转换的sheet,隐藏不需要转换的sheet
+            if (null != convertSheets) {
+                printSheetPage(wb, convertSheets);
+            }
+            // 将文件保存为PDF
+            wb.save(fileOS, pdfSaveOptions);
+            fileOS.flush();
+            fileOS.close();
+            System.out.println("convert success");
+        } catch (Exception e) {
+            System.out.println("convert failed");
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 获取生成的 pdf 文件路径,默认与源文件同一目录
+     *
+     * @param excelFilePath excel文件路径
+     * @return 生成的 pdf 文件路径
+     */
+    public static String getPdfFilePath(String excelFilePath) {
+        if (excelFilePath == null || excelFilePath.isEmpty()) {
+            throw new IllegalArgumentException("Excel file path cannot be null or empty");
+        }
+        int dotIndex = excelFilePath.lastIndexOf('.');
+        if (dotIndex > 0) {
+            return excelFilePath.substring(0, dotIndex) + ".pdf";
+        }
+        // 如果文件路径中没有扩展名,直接追加 .pdf
+        return excelFilePath + ".pdf";
+    }
+
+
+    /**
+     * 获取 license 去除水印
+     * 若不验证则转化出的pdf文档会有水印产生
+     */
+    public static void getLicense() {
+        String licenseFilePath = "excel-license.xml";
+        try {
+            InputStream is = ExcelToPdfUtils.class.getClassLoader().getResourceAsStream(licenseFilePath);
+            License license = new License();
+            license.setLicense(is);
+        } catch (Exception e) {
+            System.out.println("license verify failed");
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 隐藏workbook中不需要的sheet页。
+     *
+     * @param sheets 显示页的sheet数组
+     */
+    public static void printSheetPage(Workbook wb, int[] sheets) {
+        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
+            wb.getWorksheets().get(i).setVisible(false);
+        }
+        if (null == sheets || sheets.length == 0) {
+            wb.getWorksheets().get(0).setVisible(true);
+        } else {
+            for (int i = 0; i < sheets.length; i++) {
+                wb.getWorksheets().get(i).setVisible(true);
+            }
+        }
+    }
+
+    public static void main(String[] args) {
+//        String srcFilePath = Paths.get(FileUtils.getRootPath("fileDir"), "/templates/差旅费报销单打印模板.xlsx").toString();
+//        ExcelToPdfUtils.excel2pdf(srcFilePath);
+                ExcelToPdfUtils.excel2pdf("F:\\data\\6-2和6-3 研发支出汇总表和辅助明细账-加计扣除-8.xls");
+
+    }
+}

+ 39 - 0
src/main/java/com/goafanti/common/utils/pdf/PdfMerger.java

@@ -0,0 +1,39 @@
+package com.goafanti.common.utils.pdf;
+
+import com.itextpdf.text.Document;
+import com.itextpdf.text.pdf.PdfCopy;
+import com.itextpdf.text.pdf.PdfReader;
+
+import java.io.FileOutputStream;
+
+public class PdfMerger {
+
+    public static void main(String[] args) {
+        String[] pdfs = new String[] {
+                "F:\\data\\2-1加计扣除情况说明.pdf",
+                "F:\\data\\6-2和6-3 研发支出汇总表和辅助明细账-加计扣除-8.pdf"};
+
+        String outputPdf = "F:\\data\\merger.pdf"; // 合并后的PDF文件
+
+        try {
+            Document document = new Document();
+            PdfCopy copy = new PdfCopy(document, new FileOutputStream(outputPdf));
+            document.open();
+
+            for (String pdf : pdfs) {
+                PdfReader reader = new PdfReader(pdf);
+                for (int i = 1; i <= reader.getNumberOfPages(); i++) {
+                    document.newPage();
+                    copy.addPage(copy.getImportedPage(reader, i));
+                }
+                reader.close();
+            }
+
+            document.close();
+            System.out.println("PDFs merged successfully.");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+    }
+}

+ 70 - 0
src/main/java/com/goafanti/common/utils/word/DocToPdfUtils.java

@@ -0,0 +1,70 @@
+package com.goafanti.common.utils.word;
+
+import com.aspose.words.Document;
+import com.aspose.words.License;
+import com.aspose.words.SaveFormat;
+import com.goafanti.common.utils.LoggerUtils;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.util.Objects;
+
+
+/**
+ * word转PDF 工具类
+ *
+ */
+public class DocToPdfUtils {
+
+
+
+
+
+
+        /**
+         * 获取 license 去除水印
+         * 若不验证则转化出的pdf文档会有水印产生
+         */
+        private static void getLicense() {
+            String licenseFilePath = "word-license.xml";
+            try {
+                InputStream is = DocToPdfUtils.class.getClassLoader().getResourceAsStream(licenseFilePath);
+                License license = new License();
+                license.setLicense(Objects.requireNonNull(is));
+            } catch (Exception e) {
+                LoggerUtils.debug(DocToPdfUtils.class, "license verify failed");
+                e.printStackTrace();
+            }
+        }
+
+        /**
+         * word 转 pdf
+         *
+         * @param wordFile word 文件路径
+         * @param pdfFile  生成的 pdf 文件路径
+         */
+        public static void word2Pdf(String wordFile, String pdfFile) {
+            File file = new File(pdfFile);
+            if (!file.getParentFile().exists()) {
+                file.getParentFile().mkdir();
+            }
+            getLicense();
+            try (FileOutputStream os = new FileOutputStream(new File(pdfFile))) {
+                Document doc = new Document(wordFile);
+                doc.save(os, SaveFormat.PDF);
+            } catch (Exception e) {
+                LoggerUtils.debug(DocToPdfUtils.class, "word转pdf失败");
+                e.printStackTrace();
+            }
+        }
+
+        public static void main(String[] args) {
+//            String docFilePath = Paths.get(FileUtils.getRootPath("fileDir"), "/templates/演示文档导出.doc").toString();
+//            String pdfFilePath = Paths.get(FileUtils.getRootPath("fileDir"), "/templates/演示文档导出.pdf").toString();
+//            DocToPdfUtils.word2Pdf(docFilePath, pdfFilePath);
+              DocToPdfUtils.word2Pdf("F:\\data\\2-1加计扣除情况说明.doc", "F:\\data\\2-1加计扣除情况说明.pdf");
+        }
+
+
+}

+ 13 - 0
src/main/resources/excel-license.xml

@@ -0,0 +1,13 @@
+<License>
+  <Data>
+    <Products>
+      <Product>Aspose.Total for Java</Product>
+      <Product>Aspose.Words for Java</Product>
+    </Products>
+    <EditionType>Enterprise</EditionType>
+    <SubscriptionExpiry>20991231</SubscriptionExpiry>
+    <LicenseExpiry>20991231</LicenseExpiry>
+    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
+  </Data>
+  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
+</License>

+ 15 - 0
src/main/resources/word-license.xml

@@ -0,0 +1,15 @@
+<License>
+    <Data>
+        <Products>
+            <Product>Aspose.Total for Java</Product>
+            <Product>Aspose.Words for Java</Product>
+        </Products>
+        <EditionType>Enterprise</EditionType>
+        <SubscriptionExpiry>20991231</SubscriptionExpiry>
+        <LicenseExpiry>20991231</LicenseExpiry>
+        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
+    </Data>
+    <Signature>
+        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
+    </Signature>
+</License>