安装
npm install html2canvas
下载
import html2canvas from 'html2canvas';
html2canvas(document.getElementById(divId), {
backgroundColor: '#f1f5f8',
scale: 3,
height: document.getElementById(divId).scrollHeight,
windowHeight: document.getElementById(divId).scrollHeight,
}).then(function (canvas) {
const pngData = canvas.toDataURL('image/png');
const filename = `${name}.png`;
const anchor = document.createElement('a');
anchor.href = data;
anchor.download = filename;
anchor.click()
});
下载成PDF
import jsPDF from 'jspdf';
import { applyPlugin } from 'jspdf-autotable';
applyPlugin(jsPDF);
import html2canvas from 'html2canvas';
const height = document.getElementById(divId).scrollHeight;
html2canvas(document.getElementById(divId), {
backgroundColor: '#f1f5f8',
scale: 3,
height: height,
windowHeight: height,
}).then(function (canvas) {
const pngData = canvas.toDataURL('image/jpeg', 1.0);
const doc = new jsPDF('p', 'pt', 'a4');
const aWidth = 595.28;
const aHeight = 841.89;
const pageHeight = (aHeight * canvas.width) / aWidth;
const imgHeight = (aWidth * canvas.height) / canvas.width;
let leftHeight = canvas.height;
let position = 0;
while (leftHeight > 0) {
doc.addImage(pngData, 'JPEG', 0, position, aWidth, imgHeight);
leftHeight -= pageHeight;
position -= aHeight;
if (leftHeight > 0) {
doc.addPage();
}
}
doc.save(`${filename}.pdf`);
});
文档
html2canvas配置项文档链接