一、下载插件
npm install pdf-lib@1.17.1
npm install pdfjs-dist@2.16.105
二、在页面中引入插件
let pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js");
import workerSrc from "pdfjs-dist/legacy/build/pdf.worker.entry";
pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;
import { PDFDocument, rgb } from 'pdf-lib'
三、页面中的使用
<input type="file" class="file" id="file" ref="fielinput" @change="uploadFile" />
async uploadFile() {
let fileInput = this.$refs.fielinput;
let fileData = fileInput.files[0];
this.fileName = fileData.name;
let reader = new FileReader(); //文件读取
reader.readAsDataURL(fileData); //得到读取的文件
reader.onload = async () => { //文件加载
let data = atob(
reader.result.substring(reader.result.indexOf(",") + 1)
);
this.loadPdfData(data);
};
},
loadPdfData(data) {
// 引入pdf.js的字体
let CMAP_URL = "https://unpkg.com/pdfjs-dist@2.0.943/cmaps/";
// 读取base64的pdf流文件 返回pdf实例对象
this.pdfData = pdfjsLib.getDocument({
data: data, // PDF base64编码
cMapUrl: CMAP_URL,
cMapPacked: true,
});
// this.pdfData = pdfjsLib.getDocument(this.url)
},
// 根据页码渲染相应的PDF
renderPage() { //num传入页 返回对应页的pdf数据
this.pdfData.promise.then((pdf) => {
this.pdfPageNumber = pdf.numPages;
for (let i = 1; i <= this.pdfPageNumber; i++) {
pdf.getPage(i).then((page) => {
let canvas = document.createElement("canvas");
let viewport = page.getViewport({ scale: 3 }); //获取窗口属性
canvas.height = viewport.height;
canvas.width = viewport.width;
let ctx = canvas.getContext("2d");
let renderContext = {
canvasContext: ctx,
viewport: viewport,
};
this.$refs.canvasBox.appendChild(canvas);
let renderTask = page.render(renderContext)
renderTask.promise.then(() => {
if (this.pdfPageNumber == i) {
this.canvasFile();
}
})
});
}
});
},
//canvas 文件数据 下载
async canvasFile() {
let childNodes = this.$refs.canvasBox.childNodes;
// 创建PDF文档
const pdfDoc = await PDFDocument.create();
let y = 0;
for (let i = 0; i < childNodes.length; i++) {
// 读取PNG图片
let dataUrl = childNodes[i].toDataURL('image/png')
const img = await pdfDoc.embedPng(dataUrl);
const page = pdfDoc.addPage([595.28, 841.89])
const { width, height } = img.scaleToFit(595.28, 841.89);
page.drawImage(img, {
x: 0,
y: 0,
width: width,
height: height,
});
page.drawText('amy', {
x: width - 50,
y: 40,
size: 16,
color: rgb(0.46, 0.53, 0.6),
opacity: 1,
})
}
},
四、将签章后的PDF文档下载到本地
const pdfBytes = await pdfDoc.save()
1.文件下载插件方式一
download(pdfBytes, "pdf-lib_image_embedding_example.pdf", "application/pdf");
2.文件下载插件方式二
let blobData = new Blob([pdfBytes], { type: "application/pdf;Base64" });
let a = document.createElement("a");
a.target = "_blank";
a.href = window.URL.createObjectURL(blobData);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
文件插件链接地址:
https://gitee.com/amysunny/plug-in-unit/tree/master/