当前位置: 首页 > Web前端 > HTML5

html2canvas&&jspdf--pdf本地下载画面自定义缩放问题,只下载一页,水印,命名文件

时间:2023-04-06 00:03:25 HTML5

调用:letdomHeight=document.querySelector('#pdfDom').offsetHeighthtmlToPdfHeight.downloadPDF(document.querySelector('#pdfDom'),this.name,domHeight)下面是js文件的内容-------(typesetting可能有问题)importhtml2canvasfrom'html2canvas';importJsPDFfrom'jspdf';//只自定义一页pdf/**@paramdom生成pdf的DOM元素(容器)@parampadfName之后生成PDF文件Filename*/functiondownloadPDF(dom,pdfName,domHeight){//计算屏幕放大率varratioN=0;varscreen=window.screen;varua=navigator.userAgent.toLowerCase();if(window.devicePixelRatio!==undefined){ratioN=window.devicePixelRatio;}elseif(~ua.indexOf('msie')){if(screen.deviceXDPI&&screen.logicalXDPI){ratioN=screen.deviceXDPI/screen.logicalXDPI;}}elseif(window.outerWidth!==undefined&&window.innerWidth!==undefined){ratioN=window.outerWidth/window.innerWidth;}if(ratioN){ratioN=Math.round(ratioN*100);}varwindowScale=ratioN/100;varbox=window.getComputedStyle(dom);//DOM节点计算后的宽高//varwindowScale=box.widows;varwidth=parseInt(box.width,10)*windowScale;varheight=parseInt(box.height,10)*windowScale;//console.log(windowScale,"windowScale")//console.log(width,height,"domnode*widowsSale")//获取像素比例//constscaleBy=this.DPR();varscaleBy=1;//不放大防止屏幕文字缩放导致文件过大下载失败//创建自定义画布元素varcanvas1=document.createElement('canvas');//设置宽高canvas1.width=width*scaleBy;//注意:没有单位canvas1.height=height*scaleBy;//注意:没有单位//设置canvascss宽高为DOM节点宽高canvas1.style.width=`${width}px`;canvas1.style.height=`${height}px`;//console.log(canvas1.width,"canvas1.width00")//获取画笔varctx=canvas1.getContext("2d");//按像素比例放大所有绘图内容ctx.scale(scaleBy,scaleBy);html2canvas(dom,{dpi:300,//allowTaint:true,//允许canvas污染,allowTaint参数要去掉,否则无法通过toDataURL导出canvas数据useCORS:true,//允许跨域请求canvas外链图片,允许跨域请求height:domHeight,}).then((canvas)=>{varimg=newImage();if(img.complete){img.src=canvas.toDataURL();//由于图片是异步加载的,所以必须等待img加载完成后才能设置src属性img.onload=function(){//绘制图片ctx.drawImage(img,0,0);ctx.moveTo(0,0);ctx.lineTo(canvas1.width,canvas1.height);ctx.font="40px微软雅黑";ctx.fillStyle="rgba(0,0,0,0.1)";ctx.textAlign='居中';ctx.textBaseline='中间';ctx.rotate((-25*Math.PI)/180);//水印的初始偏转角//将水印绘制到画布上for(leti=(canvas1.height*0.5)*-1;i

最新推荐
猜你喜欢