html2canvas+jsPDF实现前端导出pdf
- 安装插件包
npm install jspdf
npm install html2canvas
- 引入插件
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
- 生成pdf
const perCanvas = document.createElement('canvas');
perCanvas.style.backgroundColor = '#fff'
const context = perCanvas.getContext('2d');
html2canvas(this.$refs.pdfContent, {
scale: 4,
dpi: 300
}).then((canvas) => {
const canvasData = canvas.toDataURL('image/jpeg', 1.0);
const pdfWidth = canvas.width;
const pdfHeight = pdfWidth * 1.414;
perCanvas.width = canvas.width;
perCanvas.height = pdfHeight;
const perHeight = pdfHeight - 100;
let splitCount = Math.ceil(canvas.height / perHeight);
if (splitCount * perHeight < canvas.height) splitCount++;
const img = new Image();
img.src = canvasData;
setTimeout(() => {
let pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]);
for (let i = 0; i < splitCount; i++) {
const startY = i * perHeight;
context.clearRect(0, 0, perCanvas.width, pdfHeight);
context.fillStyle = '#fff';
context.fillRect(0, 0, perCanvas.width, pdfHeight);
context.drawImage(img, 0, startY, perCanvas.width, perHeight, 0, 0, perCanvas.width, perHeight);
const perCanvasData = perCanvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(perCanvasData, 'JPEG', 0, 50, perCanvas.width, perCanvas.height, '', 0);
if (i < splitCount - 1) pdf.addPage();
};
let pdfBlob = pdf.output('blob');
this.showpdf = false
let signBlob = new FormData()
signBlob.append('file', pdfBlob, ".pdf")
}, 0)

- 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