将html页面转成pdf下载保存(html2canvas + jspdf或者Print调出打印功能导出pdf)
方案1:html2canvas + jspdf (缺点:清晰度不高)
安装插件: 亲测可用
yarn add html2canvas
yarn add jspdf
import html2canvas from 'html2canvas';
import jspdf from 'jspdf';
/**
*
* @param elementId dom节点id
* @param pdfName 导出的pdf文件名
* @param callback 回调函数
*/
export const htmlToPdfDownload = (elementId: any, pdfName: string, callback: any) => {
// const pageData = canvas.toDataURL('image/png');
// const pdfWidth = ((contentWidth + 10) / 2) * 0.75;
// const pdfHeight = ((contentHeight + 200) / 2) * 0.75; // 500为底部留白
// const imgWidth = pdfWidth;
// const imgHeight = pdfHeight;
// const pdf = new jspdf('', 'pt', [pdfWidth, contentHeight]);
// pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, contentHeight);
// pdf.save('report_pdf_' + new Date().getTime() + '.pdf');
const element = document.getElementById(elementId);
setTimeout(() => {
if (element) {
html2canvas(element, {
useCORS: true, // 允许加载跨域图片
// onclone: (clone) => {
// // clone 为克隆出来的整个页面的 DOM 节点
// if (elementId) {
// const cloneDOM: any = clone.getElementById(elementId);
// // 将需要下载的元素的宽度调整为 A4 纸的宽度
// // 注意:这里的操作不会修改原 DOM,因此会和页面渲染的不一致,如果需要保持和页面一致则不需要此操作
// cloneDOM.style.width = `1500px`;
// }
// },
}).then((canvas) => {
// canvas 渲染的是需要下载的元素
const pdf: any = new jspdf('p', 'pt', [592.28, 841.89]); // 创建一个 pdf
const ctx: any = canvas.getContext('2d');
const margin = 30; // pdf 每页的边距
const a4w = 592.28 - 2 * margin; // pdf 内容的宽高
const a4h = 841.89 - 2 * margin; // pdf 内容的宽高
const imgHeight = Math.floor((a4h * canvas.width) / a4w); // 将 canvas 按 pdf 内容的高度分页,imgHeight 为分页的高度
let renderedHeight = 0; // 已经添加到 pdf 的高度
while (renderedHeight < canvas.height) {
// canvas 没有全部添加到 pdf
const page: any = document.createElement('canvas'); // 创建一个新的画布
// 将 canvas 切割后渲染到新的画布上
page.width = canvas.width;
page.height = Math.min(imgHeight, canvas.height - renderedHeight);
page
.getContext('2d')
.putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
// 将新画布生成图片并添加到 pdf 中
pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', margin, margin, a4w, Math.min(a4h, (a4w * page.height) / page.width));
renderedHeight += imgHeight;
if (renderedHeight < canvas.height) {
// 如果 canvas 没有被全部添加到 pdf,则新增一页空白 pdf
pdf.addPage();
page.remove(); // 移除新的画布
}
}
// 保存 pdf
pdf.save(`${pdfName}.pdf`);
callback();
element.style.display = 'none';
// 无法理解
setTimeout(() => {
element.style.display = 'block';
}, 200);
});
}
}, 1000);
};
htmlToPdfDownload('print_pdf', '风险任务管理', () => {
message.success('下载成功');
});
<div style={{ position: 'fixed', top: 0, left: 0, zIndex: '-1', width: '1500px', height: '100%' }}>
<div id='pdf_export'> 下载的pdf </div>
</div>
方案2:Print(无需下载插件)优点:清晰度高
亲测可用,适配了echart上的图
// 打印类属性、方法定义
const Print = function (dom, options) {
if (!(this instanceof Print)) return new Print(dom, options);
this.options = this.extend(
{
noPrint: '.no-print',
},
options,
);
if (typeof dom === 'string') {
this.dom = document.querySelector(dom);
} else {
this.isDOM(dom);
this.dom = this.isDOM(dom) ? dom : dom.$el;
}
this.init();
};
Print.prototype = {
init: function () {
var content = this.getStyle() + this.getHtml();
this.writeIframe(content);
},
extend: function (obj, obj2) {
for (var k in obj2) {
obj[k] = obj2[k];
}
return obj;
},
getStyle: function () {
var str = '',
styles = document.querySelectorAll('style,link');
for (var i = 0; i < styles.length; i++) {
str += styles[i].outerHTML;
}
str += '<style>' + (this.options.noPrint ? this.options.noPrint : '.no-print') + '{display:none;}</style>';
return str;
},
getHtml: function () {
var inputs = document.querySelectorAll('input');
var textareas = document.querySelectorAll('textarea');
var selects = document.querySelectorAll('select');
let cells = document.querySelectorAll('.cell');
var canvass = document.querySelectorAll('canvas');
for (var k = 0; k < inputs.length; k++) {
if (inputs[k].type == 'checkbox' || inputs[k].type == 'radio') {
if (inputs[k].checked == true) {
inputs[k].setAttribute('checked', 'checked');
} else {
inputs[k].removeAttribute('checked');
}
} else if (inputs[k].type == 'text') {
inputs[k].setAttribute('value', inputs[k].value);
} else {
inputs[k].setAttribute('value', inputs[k].value);
}
}
for (var k2 = 0; k2 < textareas.length; k2++) {
if (textareas[k2].type == 'textarea') {
textareas[k2].innerHTML = textareas[k2].value;
}
}
for (var k3 = 0; k3 < selects.length; k3++) {
if (selects[k3].type == 'select-one') {
var child = selects[k3].children;
for (var i in child) {
if (child[i].tagName == 'OPTION') {
if (child[i].selected == true) {
child[i].setAttribute('selected', 'selected');
} else {
child[i].removeAttribute('selected');
}
}
}
}
}
//canvass echars图表转为图片
for (var k4 = 0; k4 < canvass.length; k4++) {
var imageURL = canvass[k4].toDataURL('image/png');
var img = document.createElement('img');
img.src = imageURL;
img.setAttribute('style', 'max-width: 80%;');
img.className = 'isNeedRemove';
// canvass[k4].style.display = 'none'
// canvass[k4].parentNode.style.width = '100%'
// canvass[k4].parentNode.style.textAlign = 'center'
canvass[k4].parentNode.insertBefore(img, canvass[k4].nextElementSibling);
}
const tableNode = document.querySelectorAll('.el-table__header, .el-table__body');
//el-table 打印不全的问题
for (let k6 = 0; k6 < tableNode.length; k6++) {
const tableItem = tableNode[k6];
tableItem.style.width = '100%';
const child = tableItem.childNodes;
for (let i = 0; i < child.length; i++) {
const element = child[i];
if (element.localName === 'colgroup') {
element.innerHTML = '';
}
}
}
//el-table 格子里面打印超过格子的问题
for (let k7 = 0; k7 < cells.length; k7++) {
const cell = cells[k7];
cell.style.width = '100%';
cell.removeAttribute('style');
}
//做分页
//style="page-break-after: always"
var pages = document.querySelectorAll('.result');
for (var k5 = 0; k5 < pages.length; k5++) {
pages[k5].setAttribute('style', 'page-break-after: always');
}
return this.dom.outerHTML;
},
writeIframe: function (content) {
var w,
doc,
iframe = document.createElement('iframe'),
f = document.body.appendChild(iframe);
iframe.id = 'myIframe';
//iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
iframe.setAttribute('style', 'position:absolute;width:0;height:0;top:-10px;left:-10px;');
w = f.contentWindow || f.contentDocument;
doc = f.contentDocument || f.contentWindow.document;
doc.open();
doc.write(content);
doc.close();
var _this = this;
iframe.onload = function () {
_this.toPrint(w);
setTimeout(function () {
document.body.removeChild(iframe);
}, 100);
};
},
// writeIframe: function (content) {
// var w,
// doc,
// iframe = document.createElement('iframe'),
// f = document.body.appendChild(iframe);
// iframe.id = 'myIframe';
// //iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
// iframe.setAttribute('style', 'position:absolute;width:' + document.querySelector('.results').clientWidth + 'px;height:0;top:-10px;left:-10px;');
// w = f.contentWindow || f.contentDocument;
// doc = f.contentDocument || f.contentWindow.document;
// doc.open();
// doc.write(content);
// doc.close();
// var removes = document.querySelectorAll('.isNeedRemove');
// for (var k = 0; k < removes.length; k++) {
// removes[k].parentNode.removeChild(removes[k]);
// }
// var _this = this;
// iframe.onload = function () {
// _this.toPrint(w);
// setTimeout(function () {
// document.body.removeChild(iframe);
// }, 100);
// };
// },
toPrint: function (frameWindow) {
try {
setTimeout(function () {
frameWindow.focus();
try {
if (!frameWindow.document.execCommand('print', false, null)) {
frameWindow.print();
}
} catch (e) {
frameWindow.print();
}
frameWindow.close();
}, 10);
} catch (err) {
console.log('err', err);
}
},
isDOM:
typeof HTMLElement === 'object'
? function (obj) {
return obj instanceof HTMLElement;
}
: function (obj) {
return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
},
};
// const MyPlugin = {}
export default Print;
// 下面是导出了vue上面的实例
// const MyPlugin = {}
// MyPlugin.install = function (Vue, options) {
// // 4. 添加实例方法
// Vue.prototype.$print = Print
// }
// export default MyPlugin
// print: {
// id: 'printArea',
// popTitle: '配置页眉标题', // 打印配置页上方的标题
// extraHead: '打印', // 最上方的头部文字,附加在head标签上的额外标签,使用逗号分割
// preview: true, // 是否启动预览模式,默认是false
// previewTitle: '预览的标题', // 打印预览的标题
// previewPrintBtnLabel: '预览结束,开始打印', // 打印预览的标题下方的按钮文本,点击可进入打印
// zIndex: 20002, // 预览窗口的z-index,默认是20002,最好比默认值更高
// previewBeforeOpenCallback () { console.log('正在加载预览窗口!'); console.log(that.msg, this) }, // 预览窗口打开之前的callback
// previewOpenCallback () { console.log('已经加载完预览窗口,预览打开了!') }, // 预览窗口打开时的callback
// beforeOpenCallback () { console.log('开始打印之前!') }, // 开始打印之前的callback
// openCallback () { console.log('执行打印了!') }, // 调用打印时的callback
// closeCallback () { console.log('关闭了打印工具!') }, // 关闭打印的callback(无法区分确认or取消)
// clickMounted () { console.log('点击v-print绑定的按钮了!') },
// // url: 'http://localhost:8080/', // 打印指定的URL,确保同源策略相同
// // asyncUrl (reslove) {
// // setTimeout(() => {
// // reslove('http://localhost:8080/')
// // }, 2000)
// // },
// standard: '',
// extarCss: ''
// }
import Print from '@/utils/print';
const pdfDom = document.getElementById('print_pdf');
Print(pdfDom);
// vue的
this.$nextTick(() => {
this.$print(this.$refs.print);
});