print(){            
            const iframeEL=document.querySelector('.print-iframe');
            if(iframeEL){
              iframeEL.remove();
            }
            // 获取要转换为图片的 DOM 元素
            const element = document.querySelector('.safety-inspect-form');
     
            // 将 DOM 元素转换为 Canvas 对象
            html2canvas(element).then(canvas => {
              // 创建一个新的图片元素,并将 Canvas 对象作为背景图
              const img = new Image();
              img.src = canvas.toDataURL('image/png');
              img.style.width='100%'
              img.setAttribute("crossOrigin", "anonymous");
              // 在 iframe 文档中添加图片元素
              const iframe = document.createElement('iframe');
              iframe.style.display = 'none';
              iframe.style.width='100%'
              iframe.classList.add('print-iframe')
              document.body.appendChild(iframe)
              const doc = iframe.contentWindow.document
              doc.body.appendChild(img);
              //避免图片没有加载完成就打印
              setTimeout(()=>{
                iframe.contentWindow.print();
                document.body.removeChild(iframe);
              },50)    
            })
        }

若打印页面包含第三方图片,html2canvas转图片时会不显示,我的处理方式是将第三方图片转为base64显示。

getBase64(url, callback) {
            var Img = new Image(),
            dataURL = '';
            Img.src = url +"?v=" + Math.random();
            Img.setAttribute("crossOrigin", 'Anonymous') 
            Img.onload = function () { 
                var canvas = document.createElement("canvas"), 
                width = Img.width, 
                height = Img.height;
                canvas.width = width;
                canvas.height = height;
                canvas.getContext("2d").drawImage(Img, 0, 0, width, height); 
                dataURL = canvas.toDataURL('image/jpeg'); 
                callback ? callback(dataURL) : null; 
            };
        },

html2canvas:优点不会丢失页面样式。

GitHub 加速计划 / vu / vue
207.52 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:1 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 3 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐