angular 将HTML转化为pdf文件导出、高清(不模糊)

多余废话不说直接上代码。
 
import jspdf from 'jspdf';
import html2canvas from 'html2canvas';
 
var element = $("#export-report"); // 要导出pdf的容器
var w = element.width(); // 获得该容器的宽
var h = element.height(); // 获得该容器的高
var canvas = document.createElement("canvas");
canvas.width = w * 4; // 将画布宽&&高放大n倍
canvas.height = h * 4;
var scale = 4;
const _this = this;

var opts = {
scale: scale,
canvas: canvas,
w,
height: h,
useCORS: true,
background: '#FFF'
}
html2canvas(element[0], opts).then(canvas => {
//未生成pdf的html页面高度
var leftHeight = canvas.height;
// a4纸宽高595.28 、841.89 此处为横向打印,所以宽高颠倒
var a4Width = 841.89;
var a4Height = 585.28;
//一页pdf显示html页面生成的canvas高度;
var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);
//pdf页面偏移
var position = 0;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
// p-portrait(竖向) l-landscape(横向)
var pdf = new jspdf('l', 'pt', 'a4');
var index = 1,
canvas1 = document.createElement('canvas'),
height;
pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');

var pdfName = '报告';

function createImpl(canvas) {
if (leftHeight > 0) {
index++;
var checkCount = 0;
if (leftHeight > a4HeightRef) {
var i = position + a4HeightRef;
for (i = position + a4HeightRef; i >= position; i--) {
var isWrite = true
for (var j = 0; j < canvas.width; j++) {
var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
isWrite = false
break
}
}
if (isWrite) {
checkCount++
if (checkCount >= 10) {
break
}
} else {
checkCount = 0
}
}
height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
if (height <= 0) {
height = a4HeightRef;
}
} else {
height = leftHeight;
}

canvas1.width = canvas.width;
canvas1.height = height;

var ctx = canvas1.getContext('2d');
ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);

if (position != 0) {
pdf.addPage();
}
pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 10, a4Width, a4Width / canvas1.width * height);    // 10是向下偏移10mm
leftHeight -= height;
position += height;
if (leftHeight > 0) {
setTimeout(createImpl, 500, canvas);
} else {
pdf.save(pdfName + '.pdf');
_this.MethodService.remove(tipsId);
callback();
}
}
}

//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < a4HeightRef) {
pdf.addImage(pageData, 'JPEG', 0, 10, a4Width, a4Width / canvas.width * leftHeight);
pdf.save(pdfName + '.pdf');
_this.MethodService.remove(tipsId);
callback();
} else {
try {
pdf.deletePage(0);
setTimeout(createImpl, 500, canvas);
} catch (err) {
console.log(err);
_this.MethodService.remove(tipsId);
}
}
})
 
个人意见,有更好的方法可以相互交流。欢迎留言。这种方法也有不足之处就是,是将页面转化为图片在导出PDF(和常规的PDF文件还是有不同之处)。
原文地址:https://www.cnblogs.com/jackandrose/p/15098000.html