vue3 前端实现pdf打印预览 printjs

打印 上一主题 下一主题

主题 733|帖子 733|积分 2201



  • 在utils建print.ts文件
    interface PrintFunction {
    extendOptions: Function;
    getStyle: Function;
    setDomHeight: Function;
    toPrint: Function;
    }
    const Print = function (dom, options?: object): PrintFunction {
    options = options || {};
    // @ts-expect-error
    if (!(this instanceof Print)) return new Print(dom, options);
    this.conf = {
    styleStr: “”,
    // Elements that need to dynamically get and set the height
    setDomHeightArr: [],
    // Callback before printing
    printBeforeFn: null,
    // Callback after printing
    printDoneCallBack: null
    };
    for (const key in this.conf) {
    // eslint-disable-next-line no-prototype-builtins
    if (key && options.hasOwnProperty(key)) {
    this.conf[key] = options[key];
    }
    }
    if (typeof dom === “string”) {
    this.dom = document.querySelector(dom);
    } else {
    this.dom = this.isDOM(dom) ? dom : dom.$el;
    }
    if (this.conf.setDomHeightArr && this.conf.setDomHeightArr.length) {
    this.setDomHeight(this.conf.setDomHeightArr);
    }
    this.init();
    };
    Print.prototype = {
    /**

    • init
      /
      init: function (): void {
      const content = this.getStyle() + this.getHtml();
      this.writeIframe(content);
      },
      /
      *
    • Configuration property extension
    • @param {Object} obj
    • @param {Object} obj2
      /
      extendOptions: function (obj, obj2: T): T {
      for (const k in obj2) {
      obj[k] = obj2[k];
      }
      return obj;
      },
      /
      *
      Copy all styles of the original page
      */
      getStyle: function (): string {
      let str = “”;
      const styles: NodeListOf = document.querySelectorAll(“style,link”);
      for (let i = 0; i < styles.length; i++) {
      str += styles.outerHTML;
      }
      str += <style>.no-print{display:none;}${this.conf.styleStr}</style>;
      return str;
      },
      // form assignment
      getHtml: function (): Element {
      const inputs = document.querySelectorAll(“input”);
      const selects = document.querySelectorAll(“select”);
      const textareas = document.querySelectorAll(“textarea”);
      const canvass = document.querySelectorAll(“canvas”);
    1. for (let k = 0; k < inputs.length; k++) {
    2.   if (inputs[k].type == "checkbox" || inputs[k].type == "radio") {
    3.     if (inputs[k].checked == true) {
    4.       inputs[k].setAttribute("checked", "checked");
    5.     } else {
    6.       inputs[k].removeAttribute("checked");
    7.     }
    8.   } else if (inputs[k].type == "text") {
    9.     inputs[k].setAttribute("value", inputs[k].value);
    10.   } else {
    11.     inputs[k].setAttribute("value", inputs[k].value);
    12.   }
    13. }
    14. for (let k2 = 0; k2 < textareas.length; k2++) {
    15.   if (textareas[k2].type == "textarea") {
    16.     textareas[k2].innerHTML = textareas[k2].value;
    17.   }
    18. }
    19. for (let k3 = 0; k3 < selects.length; k3++) {
    20.   if (selects[k3].type == "select-one") {
    21.     const child = selects[k3].children;
    22.     for (const i in child) {
    23.       if (child[i].tagName == "OPTION") {
    24.         if ((child[i] as any).selected == true) {
    25.           child[i].setAttribute("selected", "selected");
    26.         } else {
    27.           child[i].removeAttribute("selected");
    28.         }
    29.       }
    30.     }
    31.   }
    32. }
    33. for (let k4 = 0; k4 < canvass.length; k4++) {
    34.   const imageURL = canvass[k4].toDataURL("image/png");
    35.   const img = document.createElement("img");
    36.   img.src = imageURL;
    37.   img.setAttribute("style", "max-width: 100%;");
    38.   img.className = "isNeedRemove";
    39.   canvass[k4].parentNode.insertBefore(img, canvass[k4].nextElementSibling);
    40. }
    41. return this.dom.outerHTML;
    复制代码
    },
    /**
    create iframe
    */
    writeIframe: function (content) {
    let w: Document | Window;
    let doc: Document;
    const iframe: HTMLIFrameElement = document.createElement(“iframe”);
    const f: HTMLIFrameElement = document.body.appendChild(iframe);
    iframe.id = “myIframe”;
    iframe.setAttribute(
    “style”,
    “position:absolute;width:0;height:0;top:-10px;left:-10px;”
    );
    // eslint-disable-next-line prefer-const
    w = f.contentWindow || f.contentDocument;
    // eslint-disable-next-line prefer-const
    doc = f.contentDocument || f.contentWindow.document;
    doc.open();
    doc.write(content);
    doc.close();
    1. const removes = document.querySelectorAll(".isNeedRemove");
    2. for (let k = 0; k < removes.length; k++) {
    3.   removes[k].parentNode.removeChild(removes[k]);
    4. }
    5. // eslint-disable-next-line @typescript-eslint/no-this-alias
    6. const _this = this;
    7. iframe.onload = function (): void {
    8.   // Before popping, callback
    9.   if (_this.conf.printBeforeFn) {
    10.     _this.conf.printBeforeFn({ doc });
    11.   }
    12.   _this.toPrint(w);
    13.   setTimeout(function () {
    14.     document.body.removeChild(iframe);
    15.     // After popup, callback
    16.     if (_this.conf.printDoneCallBack) {
    17.       _this.conf.printDoneCallBack();
    18.     }
    19.   }, 100);
    20. };
    复制代码
    },
    /**
    Print
    /
    toPrint: function (frameWindow): void {
    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.error(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”
    );
    },
    /
    *
       

    • Set the height of the specified dom element by getting the existing height of the dom element and setting
    • @param {Array} arr
      */
      setDomHeight(arr) {
      if (arr && arr.length) {
      arr.forEach(name => {
      const domArr = document.querySelectorAll(name);
      console.log(name, domArr);
      domArr.forEach(dom => {
      dom.style.height = dom.offsetHeight + “px”;
      });
      });
      }
      }
      };
    export default Print;

  • .vue页面利用
    html
    1. <div class="w-full p-1" id="printApply" style="overflow: auto">
    2.   <div class="text-center text-2xl">江苏微导纳米股份有限公司</div>
    3.   <div class="text-center text-xl mb-6 mt-2">
    4.     工具出库单
    5.   </div>
    6.   <div class="flex">
    7.     <div class="flex-1 mb-2">
    8.       <div class="mb-3">事业部:{{ dataSource.chargeDept }}</div>
    9.       <div class="mb-3">班组: {{ dataSource.groupName }}</div>
    10.       <div class="">联系人: ____________________</div>
    11.     </div>
    12.     <div class="flex-1 mb-2">
    13.       <div class="mb-3">申请人:{{ dataSource.applicant }}</div>
    14.       <div class="mb-3">申请部门:{{ dataSource.applicantDept }}</div>
    15.       <div class="">联系电话: _____________________</div>
    16.     </div>
    17.     <div class="flex-1 mb-2">
    18.       <div class="mb-3">工具属性:{{ dataSource.toolProperty }}</div>
    19.       <div class="mb-3">工厂: {{ dataSource.factoryName }}</div>
    20.     </div>
    21.   </div>
    22.   <div class="my-3 w-full">
    23.     <table>
    24.       <colgroup>
    25.         <col width="50" />
    26.         <col width="120" />
    27.         <col width="150" />
    28.         <col width="150" />
    29.         <col width="100" />
    30.         <col width="100" />
    31.         <col width="100" />
    32.         <col width="100" />
    33.       </colgroup>
    34.       <tbody>
    35.         <tr height="32" class="">
    36.           <td class="text-center font-bold">序号</td>
    37.           <td class="text-center font-bold">存货编码</td>
    38.           <td class="text-center font-bold">存货名称</td>
    39.           <td class="text-center font-bold">需求时间</td>
    40.           <td class="text-center font-bold">重要程度</td>
    41.           <td class="text-center font-bold">请购用途</td>
    42.           <td class="text-center font-bold">规格型号</td>
    43.           <!-- <td class="text-center font-bold">工具大类</td> -->
    44.           <td class="text-center font-bold">申领数量</td>
    45.         </tr>
    46.         <template v-for="(item, index) in dataSource.lists">
    47.           <tr height="32">
    48.             <td class="text-center">{{ index+1 }}</td>
    49.             <td class="text-center">{{ item.cInvCode }}</td>
    50.             <td class="text-center">{{ item.cInvName }}</td>
    51.             <td class="text-center">{{ item.demandTime&&item.demandTime.slice(0, 10) }}</td>
    52.             <td class="text-center">{{ item.significance }}</td>
    53.             <td class="text-center">{{ item.purpose }}</td>
    54.             <td class="text-center">{{ item.cInvStd }}</td>
    55.             <!-- <td class="text-center">{{ item.toolType }}</td> -->
    56.             <td class="text-center">{{ item.applicationQty }}</td>
    57.           </tr>
    58.          
    59.         </template>
    60.         <tr height="32">
    61.           <td class="text-center font-bold">合计:</td>
    62.           <td colspan="6" class="text-left"></td>
    63.           <td class="text-center">{{sum}}</td>
    64.         </tr>
    65.         <tr height="65">
    66.           <td colspan="8" class="text-left ">
    67.             备注:
    68.             <br />
    69.             1、请双方确认无误后签字确认,谢谢!
    70.           </td>
    71.         </tr>
    72.       </tbody>
    73.     </table>
    74.   </div>
    75.   <div class="w-4/5 mt-2 flex justify-around">
    76.     <div class="">
    77.       <div class="">发起人签字:</div>
    78.       <div class="mt-2">发起日期:</div>
    79.     </div>
    80.     <div class="">
    81.       <div class="">审批人签字:</div>
    82.       <div class="mt-2">审批日期:</div>
    83.     </div>
    84.   </div>
    85. </div>
    复制代码
css
  1. #printApply {
  2.   display: none;
  3. }
  4. // 设置打印的时候,显示
  5. #printApply {
  6.   @media print {
  7.     display: block;
  8.   }
  9. }
  10. #printApply table {
  11.   border-top: 1px solid #333;
  12.   border-left: 1px solid #333;
  13.   border-spacing: 0;
  14.   background-color: #fff;
  15.   width: 100%;
  16. }
  17. #printApply table td {
  18.   border-bottom: 1px solid #333;
  19.   border-right: 1px solid #333;
  20.   font-size: 14px;
  21.   padding: 5px;
  22. }
复制代码
ts
  1. import {
  2.   Printer
  3. } from "@element-plus/icons-vue";
  4. import Print from "@/utils/print";
  5. const dataSource = ref({
  6.   chargeDept: "",
  7.   groupName: "",
  8.   applicant: "",
  9.   applicantDept: "",
  10.   toolProperty: "",
  11.   factoryName: "",
  12.   lists: []
  13. })
  14. let sum = 0
  15. const handlePrint = async (row) => {
  16.   sum = 0
  17.   dataSource.value = row
  18.   dataSource.value.lists.forEach((item) => {
  19.     sum += item.applicationQty
  20.   })
  21.   setTimeout(() => {
  22.     Print("#printApply").toPrint;
  23.   },500)
  24. };
复制代码
注意:在主页面打印 需要给#printApply设置隐蔽 设置打印的时候,再显示,即
  1. #printApply {
  2.   display: none;
  3. }
  4. #printApply {
  5.   @media print {
  6.    display: block;
  7.   }
  8. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

拉不拉稀肚拉稀

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表