基于SpringBoot和Jacob實現(xiàn)WPS文件的自動轉換
一、項目目錄結構
項目結構如下(lib 目錄必須存在):
wps-converter/ ├─ lib/ │ ├─ jacob.jar │ └─ jacob-1.21-x64.dll ├─ src/ │ ├─ main/java/com/donglin/ │ │ ├─ config/JacobConfig.java │ │ ├─ controller/WpsController.java │ │ ├─ service/impl/WpsServiceImpl.java │ │ ├─ utils/WpsJacobUtil.java │ │ └─ SpringbootTestApplication.java └─ pom.xml
二、pom.xml 配置
請確保你手動把 jacob.jar 放在項目的 lib 目錄下。
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>wps-converter</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<dependencies>
<!-- ? Spring Boot 基礎依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.2.5</version>
</dependency>
<!-- ? Jacob -->
<dependency>
<groupId>net.sf.jacob-project</groupId>
<artifactId>jacob</artifactId>
<version>1.21</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/jacob.jar</systemPath>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
三、JacobConfig.java
用于在 Spring Boot 啟動時加載 Jacob 的 DLL。
package com.donglin.config;
import com.jacob.com.LibraryLoader;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import java.io.File;
@Component
public class JacobConfig {
@PostConstruct
public void loadJacobDll() {
try {
// 獲取當前項目路徑
String basePath = System.getProperty("user.dir");
// 拼接DLL路徑
String dllPath = basePath + File.separator + "lib" + File.separator + "jacob-1.21-x64.dll";
System.setProperty(LibraryLoader.JACOB_DLL_PATH, dllPath);
LibraryLoader.loadJacobLibrary();
System.out.println("? Jacob DLL 已加載: " + dllPath);
} catch (UnsatisfiedLinkError e) {
System.err.println("? Jacob DLL 加載失敗: " + e.getMessage());
}
}
}
四、啟動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WpsConverterApplication {
public static void main(String[] args) {
SpringApplication.run(WpsConverterApplication.class, args);
}
}
五、WpsJacobUtil 工具類
package com.donglin.utils;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WpsJacobUtil {
/**
* 調用 WPS COM 接口,將 Word 文檔轉換為 WPS 格式
*/
public static void convertDocxToWps(String inputPath, String outputPath) {
ActiveXComponent wps = null;
try {
// "KWPS.Application" 適用于新版 WPS,舊版可嘗試 "WPS.Application"
wps = new ActiveXComponent("KWPS.Application");
wps.setProperty("Visible", new Variant(false));
Dispatch docs = wps.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs, "Open", inputPath).toDispatch();
// 6 表示 WPS 文件格式(根據版本可能不同)
Dispatch.call(doc, "SaveAs", outputPath, new Variant(6));
Dispatch.call(doc, "Close", new Variant(false));
System.out.println("? WPS 轉換成功:" + outputPath);
} catch (Exception e) {
System.err.println("? WPS 轉換失?。? + e.getMessage());
e.printStackTrace();
} finally {
if (wps != null) {
wps.invoke("Quit");
}
}
}
}
六、Service 層實現(xiàn)
package com.donglin.service.impl;
import com.donglin.utils.WpsJacobUtil;
import org.springframework.stereotype.Service;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
@Service
public class WpsServiceImpl {
public File convert(String docxPath) throws Exception {
Path src = Path.of(docxPath);
if (!Files.exists(src)) {
throw new IllegalArgumentException("源文件不存在:" + docxPath);
}
String output = src.toString().replace(".docx", ".wps");
WpsJacobUtil.convertDocxToWps(src.toString(), output);
return new File(output);
}
}
七、Controller 層接口
package com.donglin.controller;
import com.donglin.service.impl.WpsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
@RestController
public class WpsController {
@Autowired
private WpsServiceImpl wpsService;
@GetMapping("/convert")
public void convertToWps(@RequestParam String filePath, HttpServletResponse response) throws Exception {
// 防止中文路徑編碼錯誤
String decodedPath = URLDecoder.decode(filePath, StandardCharsets.UTF_8);
System.out.println("收到路徑:" + decodedPath);
// 調用 Service 進行轉換
File wpsFile = wpsService.convert(decodedPath);
// 設置響應頭
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename=" + wpsFile.getName());
response.setCharacterEncoding("UTF-8");
// 通過流返回文件
try (FileInputStream fis = new FileInputStream(wpsFile);
OutputStream os = response.getOutputStream()) {
byte[] buffer = new byte[8192];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
}
}
}
八、接口測試
使用瀏覽器調用:
GET http://localhost:8080/convert?filePath=E:/ai/report.docx
成功后瀏覽器會自動下載 report.wps 文件。
以上就是基于SpringBoot和Jacob實現(xiàn)WPS文件的自動轉換的詳細內容,更多關于SpringBoot WPS文件自動轉換的資料請關注腳本之家其它相關文章!
相關文章
深入Parquet文件格式設計原理及實現(xiàn)細節(jié)
這篇文章主要介紹了深入Parquet文件格式設計原理及實現(xiàn)細節(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
Springboot整合FreeMarker的實現(xiàn)示例
本文主要介紹了Springboot整合FreeMarker的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
解決springboot的aop切面不起作用問題(失效的排查)
這篇文章主要介紹了解決springboot的aop切面不起作用問題(失效的排查),具有很好的參考價值,希望對大家有所幫助。 一起跟隨小編過來看看吧2020-04-04
Spring源碼之事件監(jiān)聽機制詳解(@EventListener實現(xiàn)方式)
這篇文章主要介紹了Spring源碼之事件監(jiān)聽機制(@EventListener實現(xiàn)方式),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
SpringBoot使用Shiro實現(xiàn)動態(tài)加載權限詳解流程
本文小編將基于?SpringBoot?集成?Shiro?實現(xiàn)動態(tài)uri權限,由前端vue在頁面配置uri,Java后端動態(tài)刷新權限,不用重啟項目,以及在頁面分配給用戶?角色?、?按鈕?、uri?權限后,后端動態(tài)分配權限,用戶無需在頁面重新登錄才能獲取最新權限,一切權限動態(tài)加載,靈活配置2022-07-07
Feign 集成 Hystrix實現(xiàn)不同的調用接口不同的設置方式
這篇文章主要介紹了Feign 集成 Hystrix實現(xiàn)不同的調用接口不同的設置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

