请教各位大神,小程序怎么在云函数中实现word转pdf?
我尝试用了libreoffice-convert这个库,但是总是有问题,又不知道问题在哪里,把代码贴出来,请各位指教。
或者还有没有其他的方法啊?
感谢各位指点!
// 云函数入口文件
const cloud = require('wx-server-sdk')
const {
createReport
} = require('docx-templates')
const fs = require('fs')
const path = require('path')
const dayjs = require('dayjs')
const axios = require("axios")
const libre = require('libreoffice-convert')
libre.convertAsync = require('util').promisify(libre.convert)
cloud.init({
env: 'cloud1-7g1pdoii23b288bf'
})
// 云函数入口函数
exports.main = async (event, context) => {
console.log(event)
const res = await cloud.downloadFile({
fileID: event.downloadFileID,
})
const template = res.fileContent
console.log('当前下载读取文件成功')
//导入当事人签字图片并转码
let signBuffer1 = await axios({
method: 'get',
url: event.signPathLitigantURL,
responseType: 'arraybuffer',
})
const signPathLitigant64 = new Buffer.from(signBuffer1.data, 'binary').toString('base64')
//导入执法人员签字图片并转码
let signBuffer2 = await axios({
method: 'get',
url: event.signPathOfficersURL,
responseType: 'arraybuffer',
headers: { "Content-Type": "*" }
})
const signPathOfficer64 = new Buffer.from(signBuffer2.data, 'binary').toString('base64')
//导入印章图片并转码
let signBuffer3 = await axios({
method: 'get',
url: event.sealURL,
responseType: 'arraybuffer',
headers: { "Content-Type": "*" }
})
const seal64 = new Buffer.from(signBuffer3.data, 'binary').toString('base64')
//开始编译插入
const buffer = await createReport({
template,
data: {
//变量
},
additionalJsContext: {
getMapPicture1: async () => {
const res = signPathLitigant64;
return {
width: 3,
height: 1.6875,
data: res,
extension: '.png'
};
},
getMapPicture2: async () => {
const res = signPathOfficer64;
return {
width: 3,
height: 1.6875,
data: res,
extension: '.png'
};
},
getMapPicture3: async () => {
const res = seal64;
return {
width: 4,
height: 4,
data: res,
extension: '.png'
};
},
},
cmdDelimiter: ['+', '+'] //以{}作为变量分隔符
})
//开始转换PDF
const ext = '.pdf'
const pdfBuf = await libre.convertAsync(buffer, ext, undefined);
console.log('pdfBuf:',pdfBuf)
const preDir = dayjs().format("YYYYMMDD");//日期
console.log('当前的日期是',preDir)
const stringRandom = require('string-random')
const randfilename = stringRandom(32)//随机文件名
const cloudPath = `${preDir}/${randfilename}.pdf`//文件
console.log('当前云路径是',cloudPath)
return await cloud.uploadFile({
cloudPath: cloudPath,
fileContent: pdfBuf
})
}
请问这个问题解决了不讷
请问一下你的Buffer.from中的“Buffer”是从引入的什么npm包呢?我这边一直报错:Buffer is not defined。
先不运行,你说的问题是什么问题 报错?