前端js生成pdf
本文主要使用 jspdf+html2Canvas 实现 html 转 pdf。 jspdf 不支持中文 ,所以需要配合html2Canvas,先生成图片再转为pdf,就不用考虑中英文问题,但是会存在 分页 和 样式不友好 的问题
一、前期准备
1、安装 jspdf: npm install jspdf --save
2、安装 html2Canvas: npm install --save html2canvas
二、在文件中导入
import html2Canvas from 'html2canvas'; import JsPDF from 'jspdf';
三、代码函数体
// 保存 PDF
const convertCanvasToImage = () => {
// 分页
// html2Canvas(document.querySelector('#chart_table'), {
// allowTaint: true,
// }).then(function (canvas) {
// let contentWidth = canvas.width;
// let contentHeight = canvas.height;
// let pageHeight = (contentWidth / 592.28) * 841.89;
// let leftHeight = contentHeight;
// let position = 0;
// let imgWidth = 595.28;
// let imgHeight = (592.28 / contentWidth) * contentHeight;
// let pageData = canvas.toDataURL('image/jpeg', 1.0);
// let PDF = new JsPDF('', 'pt', 'a4');
// if (leftHeight < pageHeight) {
// PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
// } else {
// while (leftHeight > 0) {
// PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
// leftHeight -= pageHeight;
// position -= 841.89;
// if (leftHeight > 0) {
// PDF.addPage();
// }
// }
// }
// PDF.save('DataAnalysisResults.pdf');
// });
// 不分页
let element = document.getElementById('chart_table');
if (element) {
let width = element.offsetWidth / 4;
let height = element.offsetHeight / 4;
let limit = 14400;
if (height > limit) {
let contentScale = limit / height;
height = limit;
width *= contentScale;
}
html2Canvas(element, {
scale: 2,
useCORS: true,
allowTaint: false,
ignoreElements: (element) => {
if (element.id === 'ignoreBtnElement') return true;
return false;
}
}).then(canvas => {
let context = canvas.getContext('2d');
let orientation;
if (context) {
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
}
let pageData = canvas.toDataURL('image/jpg', 1.0);
let img = new Image();
img.src = pageData;
img.onload = function () {
img.width /= 2;
img.height /= 2;
img.style.transform = 'scale(0.5)';
let pdf;
orientation = width > height ? 'l' : 'p'
// eslint-disable-next-line
pdf = new JsPDF(orientation , 'mm', [
width,
height
]);
pdf.addImage(
pageData,
'jpeg',
0,
0,
width,
height
);
pdf.save('DataAnalysisResults.pdf');
};
});
}
};
四、不懂就问, 感谢关注, 感谢指导, 感谢吐槽