一、功能
前端html2canvas
打印 HTML页面局部打印
二、代码
结合print-js打印页面
import html2canvas from 'html2canvas';
import printJS from 'print-js';
/** 打印*/const handleDownload = async () => {console.log('inputRef.current.scrollWidth',inputRef.current.scrollWidth,inputRef.current.scrollHeight);const canvas = await html2canvas(inputRef.current, {scrollX: 0, // 水平滚动位置scrollY: 0, // 垂直滚动位置width: inputRef.current.scrollWidth, // 截取的宽度height: inputRef.current.scrollHeight, // 截取的高度useCORS: true, // 启用跨域资源支持allowTaint: true, // 允许污染图像(如果需要)scale: 1, // 缩放比例logging: true, // 开启日志输出以帮助调试backgroundColor: ' #fff', // 背景颜色(如果需要透明背景)});const dataURL = canvas.toDataURL('image/png');// 使用 printJS 打印图片printJS({printable: dataURL,type: 'image',scanStyles: false,base64: true,//方法1style: `body{margin:0}`,//方法2,需要调整,按需求修改body{margin:10px},边距style: `@media print { @page {size: auto; margin: 0; } body{margin:10px}`,,targetStyles: ['*'],});setAssignPersonType(false);};
三、容易出现的问题场景
打印指定页面元素,html2canvas先转成图片再打印,发现两页以上就会多出一页空白页
边距的原因
解决:
打印图片的时候设置下style属性,设置body{margin:0}}
或body{margin:10px}
,按照需求修改margin
//方法1style: `body{margin:0}`,//方法2,需要调整style: `@media print { @page {size: auto; margin: 0; } body{margin:10px; padding: 0;}}`,