1.引入安装依赖
npm install html2canvas --save
npm install jspdf --save
2.引入依赖
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
3.封装为函数
export const htmlPdf = async (title, html) => {
const canvas = await html2Canvas(html);
const imgData = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = imgData;
link.download = `${title}.png`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
const pdf = new JsPDF('l', 'mm', 'a4');
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
console.log('pdfWidth', pdfWidth, 'pdfHeight', pdfHeight);
console.log('html.offsetWidth', html.offsetWidth, 'html.offsetHeight', html.offsetHeight);
const imgScale = pdfWidth / html.offsetWidth;
const scaledHeight = html.offsetHeight * imgScale;
if (scaledHeight > pdfHeight) {
const maxHeightScale = pdfHeight / html.offsetHeight;
imgScale = Math.min(imgScale, maxHeightScale);
scaledHeight = pdfHeight;
}
const scaledWidth = html.offsetWidth * imgScale;
pdf.addImage(imgData, 'PNG', 0, 0, scaledWidth, scaledHeight);
pdf.save(`${title}.pdf`);
};
4.大概原理
将页面使用html2canvas转化为图片,再将图片转化为pdf