文章目录
- 1. 依赖
- 2. 工具类
- 3. 实现类
- 4. controller
- 5. application.yml
- 6. license.xml
- 7. 目录结构
- 8. 测试验证
1. 依赖
<dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version></dependency><dependency><groupId>com.aspose.cells</groupId><artifactId>aspose-cells</artifactId><version>20.4 - c</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-20.4 - c.jar</systemPath></dependency><dependency><groupId>com.aspose.words</groupId><artifactId>aspose-words</artifactId><version>words-18.10-jdk16</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-words-18.10-jdk16.jar</systemPath></dependency><!-- web支持 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>
2. 工具类
package com.gblfy.word.utils;import com.aspose.words.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;import java.io.FileOutputStream;
import java.io.InputStream;/*** 使用Aspose将word转成pdf** @author gblfy* @date 2022-11-05*/
@Slf4j
@Component
public class Word2PdfUtil {/*** 破解方法* 需要jar包: aspose-words-15.12.0-jdk16.jar* 同时配置 license.xml** @return*/private static boolean getLicense() {boolean result = false;try {InputStream is = new ClassPathResource("/license.xml").getInputStream();License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** word 转 pdf** @param inputPath word文件path(全路径)* @param outPath pdf文件path(全路径)* @return*/public Boolean word2pdf(String inputPath, String outPath) {try (FileOutputStream os = new FileOutputStream(outPath)) {if (getLicense()) {Document doc = new Document(inputPath);doc.save(os, SaveFormat.PDF);return true;}log.error("转换失败!", "破解失败");return false;} catch (Exception e) {log.error("转换失败!", e);return false;}}
}
3. 实现类
package com.gblfy.word.impl;import com.gblfy.word.utils.Word2PdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;/*** word to pdf 预览** @author gblfy* @date 2022-11-05*/
@Slf4j
@Component
public class PdfServiceImpl {@Autowiredprivate Word2PdfUtil word2PdfUtil;@Value("${word2pdf.wordDir}")private String wordDir;public void word2pdf(String fileName, HttpServletResponse response) {long start = System.currentTimeMillis();try {String wordFileName = wordDir + File.separator + fileName;String pdfFileName = fileNameHandle(wordFileName);log.info("wordFileName-》{}:" + wordFileName);log.info("pdfFileName -》{}:" + pdfFileName);File file = new File(wordFileName);if (!file.exists()) {log.error("在" + wordFileName + "目录下不存在指定文件");}// 生成pdfBoolean flag = word2PdfUtil.word2pdf(wordFileName, pdfFileName);if (flag) {byte[] buf = new byte[8 * 1024];int len = 0;try (InputStream is = new FileInputStream(pdfFileName); OutputStream os = response.getOutputStream();) {while ((len = is.read(buf, 0, buf.length)) != -1) {os.write(buf, 0, len);}os.flush();} finally {try {// 清除文件// deleteFile(wordFileName);// deleteFile(pdfFileName);} catch (Exception e) {e.printStackTrace();}}}} catch (Exception e1) {e1.printStackTrace();}long end = System.currentTimeMillis();double castTime = (end - start) / 1000.0;log.info("pdf转换成功,共耗时:->{}:" + castTime);}public String fileNameHandle(String wordFileName) {if (wordFileName.contains("docx")) {return wordFileName.replace(".docx", "pdf");}if (wordFileName.contains("doc")) {return wordFileName.replace("doc", "pdf");}return "非word格式文件,请核实!";}/*** 删除文件** @param filePath 文件* @return*/public static boolean deleteFile(String filePath) {boolean flag = false;File file = new File(filePath);// 路径为文件且不为空则进行删除if (file.isFile() && file.exists()) {file.delete();flag = true;}return flag;}
}
4. controller
package com.gblfy.word.controller;import com.gblfy.word.impl.PdfServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;/*** word to pdf 预览** @author gblfy* @date 2022-11-05*/
@RestController
public class PdfController {@Autowiredprivate PdfServiceImpl pdfService;@GetMapping("/wordtopdf/{fileName}")public void wordtopdf(@PathVariable String fileName, HttpServletResponse response) {pdfService.word2pdf(fileName, response);}
}
5. application.yml
server:port: 80
word2pdf:wordDir: D:/ht/outfilepdfDir: D:/ht/outfile
6. license.xml
<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>
7. 目录结构
8. 测试验证
在application.yml中配置文件存在的目录
http://localhost/wordtopdf/文件名称.docx