使用JSPDF打印页面以及调用浏览器打印

<el-dialog
      title="合规性校验报告"
      :visible.sync="pdfPreviewVisible"
      width="40%"
      @close="closePdfPreview"
    >
      <div class="iframe">
      //具体需要打印的页面内容
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="printPdf">打 印</el-button>
        <el-button type="primary" @click="downloadPdf">下 载</el-button>
      </span>
    </el-dialog>
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

//直接下载pdf方法
    async downloadPdf() {
      // 获取需要打印的元素
      const elements = document.getElementsByClassName("iframe");

      // 检查元素是否存在
      if (!elements || elements.length === 0) {
        this.$message.error("找不到要打印的元素");
        return;
      }

      // 获取第一个元素
      const element = elements[0];

      // 检查元素是否附加到文档
      if (!document.contains(element)) {
        this.$message.error("元素未附加到文档");
        return;
      }

      try {
        const canvas = await html2canvas(element);
        const imgData = canvas.toDataURL("image/png");

        const pdf = new jsPDF();
        const imgWidth = 210; // A4宽度
        const pageHeight = 295; // A4高度
        const imgHeight = (canvas.height * imgWidth) / canvas.width;
        let heightLeft = imgHeight;
        let position = 0;

        pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;

        while (heightLeft >= 0) {
          position = heightLeft - imgHeight;
          pdf.addPage();
          pdf.addImage(imgData, "PNG", 0, position, imgWidth, imgHeight);
          heightLeft -= pageHeight;
        }
        pdf.save("XXXXXXXXX.pdf");
      } catch (error) {
        this.$message.error("生成PDF失败: " + error.message);
      }
    },
	//调用浏览器自带的打印
    printPdf() {
      // 创建一个临时的 iframe 来处理打印
      const iframe = document.createElement("iframe");
      iframe.style.position = "absolute";
      iframe.style.top = "-1000px";
      iframe.style.left = "-1000px";
	  //这两行将 iframe 移动到页面可视区域之外(距离顶部和左侧各-1000像素),这样用户就看不到这个 iframe 了。
      document.body.appendChild(iframe);

      const printContent = document.querySelector(".iframe").innerHTML;
      const doc = iframe.contentWindow.document;
      doc.open();//获取之前创建的隐藏iframe的文档对象,并打开该文档以准备写入内容。
      doc.write(`
        <html>
          <head>
            <title></title>
            <style>
              @media print {
                body { margin: 0; }
              }
            </style>
          </head>
          <body>${printContent}</body>
        </html>
      `);
      doc.close();//关闭文档写入流,完成文档的构建。

      // 等待内容加载完成后打印
      iframe.onload = function () {
        iframe.contentWindow.focus();
        iframe.contentWindow.print();
        // 打印完成后移除 iframe
        setTimeout(() => {
          document.body.removeChild(iframe);
        }, 100);
      };
    },

学习记录,写的一般,若有错误欢迎指出

posted @ 2025-11-19 16:06  苏筱筱  阅读(0)  评论(0)    收藏  举报