1.安装
html2canvas
jspdf
cnpm install html2canvas jspdf --save -dev
cnpm或者yarn安装,使用npm可能会出现报错
2.新建htmlToPdf.js
import html2Canvas from 'html2canvas'; import JsPDF from 'jspdf'; /** * 导出为pdf文件 * @param {*} element 选中的dom元素 * @param {*} pdfTitle pdf的title * 另:这里可以更改背景色,其他的样式设置 以 元素的css为准 */ export const getPdf = (element, pdfTitle) => { const opts = { // logging: true, width: element.clientWidth, height: element.clientHeight }; html2Canvas(element, opts).then((canvas) => { const contentWidth = canvas.width; const contentHeight = canvas.height; // 一页pdf显示html页面生成的canvas高度; const pageHeight = contentWidth / 592.28 * 841.89; // 原始的canvas的html高度 let leftHeight = contentHeight; let position = 0; // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 const imgWidth = 595.28; // 根据页面的长宽,换算pdf的高度 const imgHeight = 592.28 / contentWidth * contentHeight; const pageData = canvas.toDataURL('image/jpeg', 1); const 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(`${pdfTitle}.pdf`); }); }; /** * 导出为png * @param {*} element * @param {*} title */ export const getPng = (element, title) => { const a = document.createElement('a'); html2Canvas(element).then((canvas) => { const dom = document.body.appendChild(canvas); dom.style.display = 'none'; a.style.display = 'none'; document.body.removeChild(dom); const blob = dataURLToBlob(dom.toDataURL('image/png')); a.setAttribute('href', URL.createObjectURL(blob)); a.setAttribute('download', `${title}.png`); document.body.appendChild(a); a.click(); URL.revokeObjectURL(blob); document.body.removeChild(a); }); }; export const dataURLToBlob = (dataurl) => { // ie 图片转格式 const arr = dataurl.split(','); const mime = arr[0].match(/:(.*?);/)[1]; const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); };
3.在需要页面进行引入调用 getPdf()