一、首先需要在小程序中安装两个模块,直接使用npm:
npm install pdf-lib;
npm install @pdf-lib/fontkit;
二、微信开发着工具左上角,点击:构建npm。
到了这里基本上就完成一半了,下面直接上代码
在utils文件新建pdf.js文件,这个可以随意起名
文件代码:
async function pdfFn(imgArr, isWatermark) {
const {
PDFDocument,
rgb
} = require('pdf-lib'); //引入pdf-lib模块,转成pdf的时候用到
const {
fontkit
} = require('@pdf-lib/fontkit') //引入@pdf-lib/fontkit模块,水印的时候用到
//接收小程序端传来的图片数组
let img_arr = imgArr;
//arr是用来存储fileContent的数组
let arr = [];
//pdf的总高度,是等于数组里面的所有图片的高度之和
let zheight = 0;
//用来存储处理过后的各个图片信息的数组
let content_arr = [];
const doc = await PDFDocument.create();
let page = doc.addPage();
doc.registerFontkit(fontkit);
// 下载图片 获取fileContent,并且存入arr数组
for (let i = 0; i < img_arr.length; i++) {
let lian = img_arr[i]
let sBase64 = wx.getFileSystemManager().readFileSync(lian, 'base64');
arr.push(sBase64);
};
// //获取所有照片组成的高度和宽度
for (let j = 0; j < arr.length; j++) {
//判断图片是png
if (img_arr[j].match(/.png/g)) {
let img = await doc.embedPng(arr[j]);
//计算图片展示的宽高,根据原有的比例和pdf的宽度来算
let h = (img.height * 700) / img.width;
let obj = {
img: img,
width: 700,
height: h,
};
content_arr.push(obj);
zheight = parseInt(zheight + h);
};
//判断图片是jpg
if (img_arr[j].match(/.jpg/g)) {
let img = await doc.embedJpg(arr[j]);
//计算图片展示的宽高,根据原有的比例和pdf的宽度来算
let h = (img.height * 700) / img.width;
let obj = {
img: img,
width: 700,
height: h,
};
content_arr.push(obj);
zheight = parseInt(zheight + h);
};
//判断如果图片不是png或者jpg。则返回提示
if (!img_arr[j].match(/.jpg/g) && !img_arr[j].match(/.png/g)) {
let str = '图片只支持jpg和png格式'
return str
};
};
//开始设置pdf的高度和宽度
page.setWidth(800);
page.setHeight(zheight);
//guodu_height用来存储排在前面的高度
let guodu_height = 0;
//开始绘制
for (let i = 0; i < content_arr.length; i++) {
guodu_height = guodu_height + content_arr[i].height
let height = zheight - guodu_height
page.drawImage(content_arr[i].img, {
x: 50, //左右各间隔50
y: height,
width: content_arr[i].width,
height: content_arr[i].height,
});
};
// 嵌入水印,水印不能中文,不然会报错
if (isWatermark==1) {
page.moveTo(100, zheight / 2);
page.drawText(`Identification Assistant \n` +
`\n` +
`version: 1.0.12 \n`, {
size: 50,
color: rgb(1, 0, 0),
});
page.moveDown(100);
page.drawText('Exclusive Watermark', {
size: 40,
color: rgb(1, 0, 0),
});
};
const docBase64 = await doc.saveAsBase64();
return {
docBase64,
};
}
module.exports = {
pdfFn
}
在需要的地方引入,比如:
使用:
onIdentify() {
var that = this;
wx.chooseMedia({
count: 9,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: (res) => {
const imagePath = res.tempFiles.map(res => {
return res.tempFilePath
})
pdfFn(imagePath,2).then((resl) => {
var fs = wx.getFileSystemManager();
fs.writeFile({
filePath: wx.env.USER_DATA_PATH + "/" + 'pdf名字.pdf',
data: resl.docBase64,
encoding: "base64",
success: resx => {
wx.openDocument({
filePath: wx.env.USER_DATA_PATH + "/" + 'pdf名字.pdf',
showMenu: true,
success: function (resxl) {
console.log(resxl);
},
fail(err) {
console.log(err);
}
})
}
})
})
}
})
},