使用node+libreoffice实现word批量转pdf

作者:admin
阅读量:165
更新时间:2023-01-02 18:40:16

使用node+libreoffice实现word批量转pdf,避免一个一个去转

一、准备libreoffice

在官网下载libreoffice,并配置好环境变量,使用cmd输入soffice命令弹出工作窗口即可

二、相关代码

1、核心代码

无非就是调用libreoffice来对word进行修改,自己可根据相关业务进行修改

const exec = util.promisify(require('child_process').exec);
const pdfPath=存放pdf的目录
const wordPath=word文件路径
exec('soffice --headless --convert-to pdf --outdir ' + pdfPath + ' ' + wordPath);
1
2
3
4

2、所有代码

const fs = require('fs');
const join = require("path").join;
const util = require('util');
const exec = util.promisify(require('child_process').exec);

let filename = []
let success = 0;
let fail = 0;
let exists = 0;
let text = "序号\t文件名\t状态\n"
async function init(path) {
    getFileName(path)
    console.log("转换开始...")
    for (let i = 0; i < filename.length; i++) {
        let sourcePath = (filename[i].path + "/" + filename[i].name).replace("\\", "/");
        let pdfPath = `${sourcePath.split(".")[0]}.pdf`
        let dir = (filename[i].path).replace("\\", "/")
        let isExists = fs.existsSync(pdfPath);
        if (isExists) {
            exists++;
            text = `${text}${i+1}\t${sourcePath}\t已存在\n`
            console.log(`${sourcePath}  转换成功(共${filename.length}个文件,${success}成功,${exists}存在,${fail}失败) `)
        } else {
            const data = await wordToPdf(sourcePath, dir)
            if (data) {
                text = `${text}${i+1}\t${sourcePath}\t成功\n`
                success++;
            } else {
                text = `${text}${i+1}\t${sourcePath}\t失败\n`
                fail++
            }
            console.log(`${sourcePath}  转换成功(共${filename.length}个文件,${success}成功,${exists}存在,${fail}失败) `)
        }

    }
    text = `${text}统计\t共${filename.length}个文件,${success}成功,${exists}存在,${fail}失败`
    fs.writeFileSync(`./${getLogName()}.txt`, text)

}


function getFileName(path) {
    const files = fs.readdirSync(path)
    files.forEach(item => {
        let fPath = join(path, item);
        let stat = fs.statSync(fPath);
        if (stat.isDirectory()) {
            getFileName(fPath)
            return true;
        }
        if (!stat.isFile()) {
            return false;
        }
        let suffix = item.split(".")[1].toLowerCase();
        if (!(suffix === "docx" || suffix === "doc")) {
            return false
        }
        filename.push({
            path: path,
            name: item
        })
    })
}

async function wordToPdf(wordPath, pdfPath) {
    const {
        stderr
    } = await exec('soffice --headless --convert-to pdf --outdir ' + pdfPath + ' ' + wordPath);
    if (stderr === "") {
        return true;
    } else {
        return false;
    }
}

function getLogName() {
    let d = new Date()
    return `${d.getFullYear()}${d.getMonth()}${d.getDate()}${d.getHours()}${d.getMinutes()}${d.getSeconds()}`
}

init("./")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

三、执行

使用node index.js即可执行程序