前端页面怎么导出为pdf?

数据后台返回了,数据渲染在一个dialog中,现在想把这个dialog中的内容导出成一个pdf,请问怎么实现,有什么方法可以实现

阅读 2.6k
3 个回答

安装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) {

Vue.prototype.getPdf = function() {
  var title = this.htmlTitle;
  html2Canvas(document.querySelector("#pdfDom"), {
    allowTaint: true
  }).then(function(canvas) {
    let contentWidth = canvas.width;
    let contentHeight = canvas.height;
    let pageHeight = (contentWidth / 592.28) * 841.89;
    let leftHeight = contentHeight;
    let position = 0;
    let imgWidth = 595.28;
    let imgHeight = (592.28 / contentWidth) * contentHeight;
    console.log(imgHeight);
    let pageData = canvas.toDataURL("image/jpeg", 1.0);
    let 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(title + ".pdf");
  });
};

}
};
在需要打印的页面用标签包裹
<div class="row" id="pdfDom" style="padding-top: 20px; background-color: #fff">
需要打印的内容
</div>
<el-button type="primary" @click="getPdf()">导出</el-button>

就ok了

可以拿到 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>

jsPDF.JS,canvas以及html都可以导出

推荐问题