web123456

vue prints page (solves the problem of incomplete print preview)

<template> <div> <el-button class="acticedBtn" @click="printFn">Print</el-button> <div ref="printId">Printed content</div> </div> </template> <script> import printJS from 'print-js'; import html2canvas from 'html2canvas'; export default { methods:{ printFn(){ const printContent = this.$refs.printId; // Get dom width Height const width = printContent.clientWidth; const height = printContent.clientHeight; // Create a canvas node const canvas = document.createElement('canvas'); const scale = 4; // Define any magnification ratio and support decimals; the larger the image, the higher the image definition and the slower the image is generated. canvas.width = width * scale; // Define the canvas width * Scale canvas.height = height * scale; // Define canvas height *Scale canvas.style.width = width * scale + 'px'; canvas.style.height = height * scale + 'px'; canvas.getContext('2d').scale(scale, scale); // Get context, set scale const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // Get the length of the scroll axis const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; // Get the length of the horizontal scroll axis html2canvas(printContent, { canvas, backgroundColor: null, useCORS: true, windowHeight: document.body.scrollHeight, scrollX: -scrollLeft, // Solve the horizontal offset problem and prevent incomplete printed content scrollY: -scrollTop }).then((canvas) => { const url = canvas.toDataURL('image/png') printJS({ printable: url, type: 'image', documentTitle: '', // Title style: '@page{size:auto;margin: 0cm 1cm 0cm 1cm;}' // Remove header footer }) }).catch(err=>{ console.error(err); }) } } } </script>