如何使用 JavaScript 和 nodejs 将 docx 文件转换为 pdf 文件
在这篇文章中,你将学习如何用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);
});
同样的代码也可以用async和await关键字来写异步过程。
异步和等待
这对尺寸较大的文件很有用
声明的函数接受输入和输出的文件名,如果转换失败则返回承诺对象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文件
上一篇: word翻出图像(使用免费插件) 01
下一篇: 域名可以转移到其他平台吗?
推荐阅读
-
35 岁实现财务*,腾讯程序员手握2300万提前退休?-1000万房产、1000万腾讯股票、加上300万的现金,一共2300万的财产。有网友算了一笔账,假设1000万的房产用于自住,剩下1300万资产按照平均税后20-50万不等进行计算,大约花上26-60年左右的时间才能赚到这笔钱。也就是说,普通人可能奋斗一辈子,才能赚到这笔钱。在很多人还在为中年危机而惶惶不可终日的时候,有的人的35岁,就已经安全着陆,试问哪个打工人不羡慕?但问题是有这样财富积累必然有像样的实力做靠山。没有人可以不劳而获。 看到这里,肯定有人说,那么对于普通人来说,卷可能真就成了唯一的出路。但是卷也有轻松的卷,“偷懒”的卷法,对于程序员而言,刨除掉一时无法改掉的开会传统占用的大部分时间,如何把有限的时间和精力放在真正重要的架构设计、需求设计上,而不是重复的造*,编码、改bug、手动测试。因此在科技改变生活的今天,学会使用AI工具成为程序员们的必备技能。 以全栈式全自动的软件开发工具飞算SoFlu软件机器人为例,作为全球首款面向微服务架构设计和最佳实践的软件机器人,SoFlu软件机器人改变了原来手工编码的作业模式,通过可视化拖拽方式以及参数配置就能实现等同于编写复杂代码的业务逻辑,在设计业务逻辑时就完成了微服务应用开发,做到“业务即图,图即代码”,实现“软件开发,十倍提效”。 而作为飞算SoFlu软件机器人的一个重要组成部分,FuncGPT(慧函数)支持所有类型函数创建。通过自然语言描述Java函数需求,实时生成高质量、高可读性的Java函数代码。生成代码可直接复制到IDEA,或一键导入Java全自动开发工具函数库。 FuncGPT(慧函数)具有五大核心能力: ● 自然语言:通过自然语言即可生成函数,降低软件开发门槛。 ● 秒级函数开发:全自动秒级开发函数,秒级完成,效率千倍提升。 ● 一站式函数开发应用:函数生成即可直接应用,效率、安全有保障。 ● 质量可靠:生成的函数代码符合业界规范、具备良好的可读性,符合最优解。 ● 灵活生成:可以根据开发人员的具体需求生成并支持调整和修改。 以“将文件流转换为File对象”这个需求为例,以下是FuncGPT(慧函数)秒级生成的代码: / 类名:FileConverter // 函数名:convertStreamToFile // 函数功能:将文件流转换为File对象 // POM依赖包:无 import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class FileConverter { /** * 将文件流转换为File对象 * @param inputStream 文件流 * @param filePath 文件路径 * @param fileName 文件名 * @return 转换后的File对象 * @throws IOException 如果发生I/O异常 */ public static File convertStreamToFile(InputStream inputStream, String filePath, String fileName) throws IOException { File file = new File(filePath + File.separator + fileName); // 创建File对象 try (FileOutputStream outputStream = new FileOutputStream(file)) { // 创建文件输出流 byte buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { // 从文件流读取数据并写入文件 outputStream.write(buffer, 0, bytesRead); } } return file; // 返回转换后的File对象 } } // 函数示例 // 将文件流转换为File对象示例 // 入参:inputStream,文件流 // 入参:filePath,文件路径 // 入参:fileName,文件名 // 出参:file,转换后的File对象 // 调用示例: // InputStream inputStream = new FileInputStream("example.txt"); // String filePath = "C:\\Users\\User\\Documents"; // String fileName = "example.txt"; // File file = FileConverter.convertStreamToFile(inputStream, filePath, fileName); // System.out.println(file.getAbsolutePath); // 输出结果:例如,将文件流转换为File对象后,文件的绝对路径为:C:\Users\User\Documents\example.txt // 则输出结果为:C:\Users\User\Documents\example.txt 通过分析,不难发现以上代码:
-
Java 类加载器的作用 - 简介:类加载器是 Java™ 中一个非常重要的概念。类加载器负责将 Java 类的字节码加载到 Java 虚拟机中。本文首先详细介绍了 Java 类加载器的基本概念,包括代理模型、加载类的具体过程和线程上下文类加载器等。然后介绍了如何开发自己的类加载器,最后介绍了类加载器在 Web 容器和 OSGi™ 中的应用。 类加载器是 Java 语言的一项创新,也是 Java 语言广受欢迎的重要原因之一。它允许将 Java 类动态加载到 Java 虚拟机中并执行。类加载器从 JDK 1.0 开始出现,最初是为了满足 Java Applets 的需求而开发的,Java Applets 需要从远程位置下载 Java 类文件并在浏览器中执行。现在,类加载器已广泛应用于网络容器和 OSGi。一般来说,Java 应用程序的开发人员不需要直接与类加载器交互;Java 虚拟机的默认行为足以应对大多数情况。但是,如果遇到需要与类加载器交互的情况,而您又不太了解类加载器的机制,就很容易花费大量时间调试异常,如 ClassNotFoundException 和 NoClassDefFoundError。本文将详细介绍 Java 的类加载器,帮助读者深入理解 Java 语言中的这一重要概念。下面先介绍一些基本概念。 类加载器的基本概念 顾名思义,类加载器用于将 Java 类加载到 Java 虚拟机中。一般来说,Java 虚拟机以如下方式使用 Java 类:Java 源程序(.java 文件)经 Java 编译器编译后转换为 Java 字节代码(.class 文件)。类加载器负责读取 Java 字节代码并将其转换为 java.lang 实例。每个实例都用来表示一个 Java 类。通过该实例的 newInstance 方法创建该类的对象。实际情况可能更加复杂,例如,Java 字节代码可能是由工具动态生成或通过网络下载的。 基本上,所有类加载器都是 java.lang.ClassLoader 类的实例。下面将详细介绍这个 Java 类。 java.lang.ClassLoader 类简介 java.lang.ClassLoader 类的基本职责是根据给定类的名称为其查找或生成相应的字节码,然后根据这些字节码定义一个 Java 类,即 java.lang.Class 类的实例。除此之外,ClassLoader 还负责加载 Java 应用程序所需的资源,如图像文件和配置文件。不过,本文只讨论它加载类的功能。为了履行加载类的职责,ClassLoader 提供了许多方法,其中比较重要的方法如表 1 所示。下文将详细介绍这些方法。 表 1.与加载类相关的 ClassLoader 方法
-
如何使用 JavaScript 和 nodejs 将 docx 文件转换为 pdf 文件
-
南邮OJ Web任务大揭秘:层层挑战剖析 1. 挑战一:迷宫般的目录探索 题目作者似乎穷举了所有可能的目录组合,最终在404.php中的