Chrysanthemum printing

Time:2020-10-30

Front end to achieve partial printing is to print part of the page information through the printer
It mainly relies on html2canvas, a tripartite tool, and window.print Native API
Html2canvas: the main function of this tool is to pass in the DOM to get a screenshot of the dom
window.print : call up the printer to print the page
preparation

npm install --save html2canvas

Specific use
. Vue section

<div class="print">
      <p>Parts to be printed</p>
      <p>Parts to be printed</p>
      <p>Parts to be printed</p>
    </div>
    <div>
      <p>Parts that will not print</p>
      <p>Parts that will not print</p>
      <p>Parts that will not print</p>
    </div>
    <div class="print">
      <p>Parts to be printed</p>
      <p>Parts to be printed</p>
      <p>Parts to be printed</p>
    </div>

. JS section

print() {
      const domList = [... document.querySelectorAll (". Print")]; // the identified class name will be given to the part to be printed
      const imgList = [];
      const count = 0;
      const fn = () => {
        /**
         *Open the new page and append the image, and then call the print of the new page
         */
        const printWindow = window.open();
        imgList.forEach(img => {
          printWindow.document.body.append(img);
        });
        printWindow.print();
      };

      domList.forEach(dom => {
        //Html2canvas does not support list, so go through it
        html2canvas(dom).then(canvas => {
          /**
           *Html2canvas accepts Dom and generates canvas, which can be converted into pictures for printing
           */
          const base64 = canvas.toDataURL();
          const img = new Image();
          img.onload = function() {
            /**
             *Because printing multiple parts will generate multiple images, which are also orderly, so this operation is available
             */
            imgList[i] = this;
            count++;
            if (count >= domList.length) {
              fn();
            }
          };
          img.src = base64;
        });
      });
    },

Why do you do this?
If you directly call the print method on this page, the entire page will be printed. If you want to achieve partial printing, you need to hide the unnecessary part of the trouble
The advantage of this method is that it does not have to be tedious to configure. You only need to generate images for the part to be printed, and then throw the generated images into the newly opened page. The newly opened page only needs to be printed. At this time, it is perfect to call the print method of the new page
Finally, the printing effect is OK. Anyway, the product is accepted. Ha ha