点击按钮实现打印页面选定内容
调用系统的打印方法会发现直接把整个页面都进行了打印,不可行。
- 在布局上需要把进行打印的内容单独放置在某元素内
<el-button type="primary" class="print" @click="printData">打印个人档案</el-button>
<div id="printDiv" ref="printDiv">
进行打印的内容
</div>
<iframe width="0" height="0" frameborder="0" id="printIframe"></iframe>
- 点击按钮进行打印
/* 打印个人档案 */
const printData = () => {
//获取打印内容
const printHtml = document?.getElementById("printDiv")?.innerHTML;
//获取iframe 标签
const syfPrint = document?.getElementById("printIframe") as HTMLIFrameElement | null;
if (syfPrint) {
//获取原页面里的head标签
const documentHead = document.getElementsByTagName("head")[0];
//获取iframe 页面里的head标签
const iframeHead = syfPrint.contentDocument?.getElementsByTagName("head")[0];
//把原页面的里的head标签内容给到iframe 页面里的head
if (iframeHead) {
iframeHead.innerHTML = documentHead.innerHTML;
}
//获取iframe 页面里的body,然后把dom结构赋值给iframe
const syfPrintBody = syfPrint.contentDocument?.body;
if (syfPrintBody) {
syfPrintBody.innerHTML = printHtml || "";
//执行打印
syfPrint.contentDocument.execCommand("Print");
}
} else {
//错误提示
message.error(t('打印错误'));
}
}