【求助】如何用Nodejs生成2003的word文档,或者生成07的文档后有啥办法转到03呢?

【求助】如何用Nodejs生成2003的word文档,或者生成07的文档后有啥办法转到03呢?

如题,求助各位有没有类似经历的,客户非要生成.doc的文件,真愁人啊。。

目前解决方案是用的officegen,能生成docx,但网站上写了支持07以及later版本。。

3 回复

要使用 Node.js 生成 .doc(Word 2003 格式)或 .docx(Word 2007 及之后格式),你可以使用一些现有的库。对于生成 .docx 文件,officegen 是一个常用的选择。但是,由于 .doc 文件不被广泛支持且复杂度较高,直接生成 .doc 文件并不容易。我们可以先生成 .docx 文件,然后通过第三方工具将其转换为 .doc 文件。

使用 officegen 生成 .docx 文件

首先,你需要安装 officegen 库:

npm install officegen

接下来,我们可以编写一段简单的代码来生成一个 .docx 文件:

const officegen = require('officegen');

// 创建一个新的 Word 文档
const docx = officegen({
  type: 'docx'
});

// 添加一些段落
docx.on('generate', (written) => {
  console.log(`Generated: ${written} bytes`);
});

docx.createP().text('Hello, this is a test paragraph!');

// 保存文档
const out = fs.createWriteStream('test.docx');
out.on('close', () => {
  console.log('Done!');
});

docx.generate(out);

将 .docx 转换为 .doc

为了将 .docx 文件转换为 .doc 文件,你可以使用一些外部工具,例如 antiwordabiword。这些工具通常需要在服务器上安装,并通过命令行调用。

使用 abiword 进行转换

首先,在你的系统上安装 abiword

sudo apt-get install abiword

然后,你可以使用 Node.js 的子进程功能来调用 abiword 命令进行转换:

const { exec } = require('child_process');

exec('abiword --to=doc test.docx', (error, stdout, stderr) => {
  if (error) {
    console.error(`执行出错: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.error(`stderr: ${stderr}`);
});

这段代码会将 test.docx 转换为 test.doc 文件。

总结

虽然直接生成 .doc 文件比较困难,但你可以先生成 .docx 文件,然后使用 abiword 等工具将其转换为 .doc 文件。这种方法可以满足大多数需求,尽管可能需要在服务器上安装额外的软件。


没有试过, 但是试试这个思路呢?(google关键字 “libreoffice service”) http://www.linuxquestions.org/questions/blog/sag47-492023/headless-file-conversion-using-libreoffice-as-a-service-35310/ 起一个OpenOffice或者LiberOffice的后台服务做逻辑,然后写nodejs做通信

生成符合 .doc 格式的 Word 文档在 Node.js 中并不是一件直接的事情,因为许多库主要支持 .docx 格式。不过,你可以先生成 .docx 文件,然后使用一些转换工具将其转换为 .doc 格式。

使用 officegen 生成 .docx 文件

首先,你需要安装 officegen 库来生成 .docx 文件:

npm install officegen

以下是一个简单的示例代码,用于生成一个 .docx 文件:

const officegen = require('officegen');

function createDocx() {
    const docx = officegen({
        type: 'docx',
        author: 'Your Name'
    });

    const para1 = docx.createP();
    para1.addText('This is the first paragraph.');

    const para2 = docx.createP();
    para2.addText('This is the second paragraph.', { bold: true });

    const out = fs.createWriteStream('output.docx');
    docx.generate(out);
}

createDocx();

将 .docx 转换为 .doc

你可以使用外部工具(如 Antiword 或 catdoc)将 .docx 文件转换为 .doc 格式。这些工具通常只能在类 Unix 系统(如 Linux 或 macOS)中运行。

在 Linux 上使用 docx2txtantiword

  1. 安装 docx2txtantiword
sudo apt-get install docx2txt antiword
  1. 使用 docx2txt 提取文本内容,然后使用 antiword 转换为 .doc 格式:
docx2txt output.docx - | antiword - > output.doc

总结

虽然 Node.js 本身没有直接生成 .doc 文件的库,但你可以先生成 .docx 文件,然后通过命令行工具进行转换。这需要在服务器端配置相应的工具,并且可能需要额外的步骤来处理文件。如果你的需求是完全在 Node.js 中完成这一过程,可能需要寻找或开发更底层的库来实现这一功能。

回到顶部