You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js中使用libreoffice-convert将PDF转为DOCX?

使用libreoffice-convert实现PDF转DOCX的完整步骤

1. 前置依赖准备

  • 确保系统已安装LibreOffice(该工具依赖LibreOffice的命令行组件),Windows/macOS/Linux均支持,安装后需保证soffice命令能在终端直接调用,若不行则将LibreOffice安装目录添加到系统PATH。
  • 本地需具备Node.js环境(建议版本14及以上)。

2. 安装npm包

在Node.js项目根目录执行:

npm install libreoffice-convert

3. 代码使用说明

步骤1:准备文件结构

在项目根目录创建resources文件夹,将需要转换的PDF文件(示例中为example.pdf)放入该文件夹。

步骤2:创建转换脚本

新建一个JS文件(比如命名为convert.js),复制以下示例代码:

const path = require('path');
const fs = require('fs').promises;

const libre = require('libreoffice-convert');
libre.convertAsync = require('util').promisify(libre.convert);

async function main() {
    const ext = '.docx'
    const inputPath = path.join(__dirname, '/resources/example.pdf');
    const outputPath = path.join(__dirname, `/resources/example${ext}`);
    const file = await fs.readFile(inputPath);
    // 若系统找不到soffice命令,可在第三个参数配置路径,例如 { sofficePath: '/usr/bin/soffice' }
    let conv = await libre.convertAsync(file, ext, undefined);
    await fs.writeFile(outputPath, conv);
    console.log('转换完成!');
}

main().catch(function (err) {
    console.log(`Error converting file: ${err}`);
});

步骤3:运行脚本

在终端执行:

node convert.js

运行结束后,resources文件夹内会生成转换好的example.docx文件。

常见问题提示

  • 若报错提示找不到soffice命令:检查LibreOffice是否安装,或在convertAsync的第三个参数手动指定soffice路径,例如:
    // Windows示例路径
    let conv = await libre.convertAsync(file, ext, { sofficePath: 'C:\\Program Files\\LibreOffice\\program\\soffice.exe' });
    // macOS示例路径
    let conv = await libre.convertAsync(file, ext, { sofficePath: '/Applications/LibreOffice.app/Contents/MacOS/soffice' });
    

内容的提问来源于stack exchange,提问作者istdio inc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:05:24