javascript
复制代码
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);
// pdf的尺寸
const pdfWidth = canvas.width;
const pdfHeight = pdfWidth * 1.414;
//切割后的canvas图片的宽高,就等于每页pdf的宽高
perCanvas.width = canvas.width;
perCanvas.height = pdfHeight;
// 每张图片的高度:适当减少100,上下各留50页边距
const perHeight = pdfHeight - 100;
// 计算切割次数
let splitCount = Math.ceil(canvas.height / perHeight);
if (splitCount * perHeight < canvas.height) splitCount++;
//创建img对象,加载完整的canvas图片
const img = new Image();
img.src = canvasData;
//创建pdf对象
//待图片加载完成
setTimeout(() => {
let pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]);
//切割canvas图片,贴到每一页pdf中
for (let i = 0; i < splitCount; i++) {
const startY = i * perHeight; // 起始y坐标
// 清空画布
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');
// pdf.save("content.pdf"); 执行此api会直接下载
this.showpdf = false
let signBlob = new FormData() //把文件上传到后台
signBlob.append('file', pdfBlob, ".pdf")
//此处将signBlob上传即可
}, 0)