数据后台返回了,数据渲染在一个dialog中,现在想把这个dialog中的内容导出成一个pdf,请问怎么实现,有什么方法可以实现
可以拿到 dialog 里的 html,然后塞进一个新创建 iframe 里面,再调用 iframe.contentWindow.print() 就可以调起浏览器的打印啦
<body>
<dialog id="dialog">
<div>hello world</div>
<button id="print">打印</button>
</dialog>
<script>
const dialogDom = document.querySelector('#dialog');
const btnDom = document.querySelector('#print');
dialogDom.showModal();
btnDom.addEventListener('click', e => {
const iframe = document.createElement('iframe');
iframe.style = 'display: none';
document.body.append(iframe);
iframe.contentDocument.body.innerHTML = dialog.innerHTML;
iframe.contentWindow.print();
document.body.removeChild(iframe);
});
</script>
</body>
13 回答12.7k 阅读
8 回答2.4k 阅读
2 回答5k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
5 回答747 阅读
3 回答2.1k 阅读
2 回答1.5k 阅读✓ 已解决
安装html2canvas和jspdf;
在main.js中注册
import htmlToPdf from "@/utils/htmlToPdf";
Vue.use(htmlToPdf);
在utils中创建一个js文件
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export default {
install(Vue, options) {
}
};
在需要打印的页面用标签包裹
<div class="row" id="pdfDom" style="padding-top: 20px; background-color: #fff">
需要打印的内容
</div>
<el-button type="primary" @click="getPdf()">导出</el-button>
就ok了