java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot WPS文件自动转换

基于SpringBoot和Jacob实现WPS文件的自动转换

作者:Knight_AL

本文详细介绍了如何使用SpringBoot和Jacob实现WPS文件的自动转换,主要步骤包括配置项目目录、pom.xml、加载DLL、启动类、工具类、Service层和Controller层接口,最终,通过浏览器调用接口,可以下载转换后的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 层实现

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实现WPS文件的自动转换的详细内容,更多关于SpringBoot WPS文件自动转换的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文