欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

如何使用 JavaScript 和 nodejs 将 docx 文件转换为 pdf 文件

最编程 2024-03-01 19:03:04
...

在这篇文章中,你将学习如何用JavaScript和nodejs将docx文件转换成pdf文件。

Docx/doc是微软公司的文件格式,包含图像、文本、表格和样式PDF文件是Adobe公司的,它是代表图像、文本和样式内容的独立格式。

有很多在线工具可以将doc转换为pdf。有时,作为一个程序员,你需要在JavaScript/NodeJS应用程序中进行不同格式的转换。

JavaScript/NodeJS提供了多种使用npm包进行转换的方法

  • docx-to-pdf
  • libreoffic-convert

首先,从头开始创建一个Nodejs应用程序。

让我们在新文件夹中使用npm init -y command ,从头开始创建nodejs应用程序

B:\blog\jswork\nodework\doctopdf>npm init -y
Wrote to B:\blog\jswork\nodework\doctopdf\package.json:

{
  "name": "doctopdf",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

这将创建一个package.json,如下所示

{
  "name": "doctopdf",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

使用docx-pdf方法

docx-pdf是一个将docx转换为pdf文档的简单库。

首先,安装docx-pdf npm库

npm install docx-pdf --save

这将在package.json中添加一个依赖项,如下所示

{
 "dependencies": {
    "docx-pdf": "0.0.1"
  }
}

在javascript中使用Require为ES5模块导入docx-pdf

var converter = require('docx-pdf');

转换对象接受输入文件,即word文档 输出文件是pdf文档的名称 回调,其中有err 转换失败的错误信息和转换成功的结果 结果是一个包含文件名属性的对象,值是pdf文档的名称和路径

var converter = require('docx-pdf');

converter('test.docx', 'output.pdf', function(err, result) {
    if (err) {
        console.log("Converting Doc to PDF  failed", err);
    }
    console.log("Converting Doc to PDF succesfull", result);
});

同样的代码也可以用asyncawait关键字来写异步过程。

异步和等待

这对尺寸较大的文件很有用

声明的函数接受输入和输出的文件名,如果转换失败则返回承诺对象reject ,转换成功则返回resolve 。而且,docxConverter逻辑是在async 关键字内调用匿名函数进行异步处理。

    async function ConvertDocToPdf(inputfile, outputfile) {
            return new Promise((resolve, reject) =>{
                        const inputPath = path.join(__dirname, "test.docx");
        const outputPath = path.join(__dirname, `/test.pdf`);
        let docData = await fs.readFile(inputPath)
                docxConverter(inputfile, outputfile, (err, result) => {
                    return err ?
                        reject(err) :
                        resolve(result)
                })
            })
        }

你需要用await 关键字来调用同一个函数:

    await ConvertDocToPdf("test.docx", "test.pdf")

这是一个简单的库,唯一的缺点是不能转换格式样式。

libreoffic-convert npm包

libreoffice是开源的办公软件包,用于管理办公文件。

libreoffic-convert是一个npm包,在nodejs中提供对word文档的操作。

首先使用npm install命令安装libreoffice-convertnpm包。

npm install libreoffice-convert --save

使用libreoffic-convert包将docx转换成pdf的代码示例。

const libre = require('libreoffice-convert');
const path = require('path');
const fs = require('fs');

async function ConvertDocToPdf() {
    try {
        const inputPath = path.join(__dirname, "test.docx");
        const outputPath = path.join(__dirname, `/test.pdf`);
        let docData = await fs.readFile(inputPath)
        return new Promise((resolve, reject) => {
            libre.convert(docData, '.pdf', undefined, (err, done) => {
                if (err) {
                    reject('Convertion Failed')
                }
                fs.writeFileSync(outputPath, done);
                resolve("Convertion successfull")

            });
        })
    } catch (err) {
        console.log("Error in input reading", err);
    }
}

上述代码的步骤顺序:

  • 用async关键字定义函数进行异步处理
  • 在代码中导入libreoffic-convert、fs和path模块
  • 使用NodeJS中fs模块的readFile方法读取输入文件
  • libre.convert将docx转换成pdf文件
  • 转换代码被包裹在承诺对象中
  • 对于转换失败的情况,会返回拒绝承诺
  • 对于成功的转换,承诺被解决
  • 最后使用writeFileSync 方法写入输出的pdf文件

推荐阅读