一、功能
前端html2canvas
打印 HTML页面局部打印
二、代码
import html2canvas from 'html2canvas';
/**
* 打印
*/
const handleDownload = async () => {
const canvas = await html2canvas(inputRef.current, {
scale: 1, // 提高分辨率--缩放
logging: true, // 开启日志
useCORS: true, // 允许跨域图片
allowTaint: true, // 允许污染画布
backgroundColor: '#ffffff', // 背景色
});
const dataURL = canvas.toDataURL('image/png');
// 创建一个新窗口用于打印
const printWindow = window.open('', '_blank');
// 将canvas添加到新窗口
printWindow.document.write('<html><head><title>打印</title></head><body>');
printWindow.document.write('<img src="' + canvas.toDataURL('image/png') + '"/>');
printWindow.document.write('</body></html>');
// 关闭文档写入
printWindow.document.close();
// 等待图片加载完成后打印
printWindow.onload = function () {
printWindow.print();
// 可选:打印后关闭窗口
printWindow.close();
};
};
三、容易出现的问题场景
当使用 html2canvas 打印页面时遇到滚动条
和内容打印不全
的问题
注意:
(临时修改后的样式要刚好
在屏幕可视区域
)
因为html2canvas
默认只会截取
当前可视区域
的内容
如果超出部分
请再结合方法二
使用方法
解决
方法1:
打印时 临时
修改样式,打印后恢复
原来样式
创建打印状态 handleDownloadType
:Boolean
//打印 状态
const [handleDownloadType, setAssignPersonType] = useState(false);
useEffect(() => {
if (handleDownloadType) {
//true是打印页面
handleDownload();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [handleDownloadType]);
// 等待图片加载完成后打印
printWindow.onload = function () {
printWindow.print();
// 可选:打印后关闭窗口
printWindow.close();
//打印后状态false
setAssignPersonType(false)
};
//handleDownloadType 使用
<div
className="form"
style={{
height: handleDownloadType ? '100%' : 'calc(100% - 64px)',
overflow: handleDownloadType ? 'hidden' : 'auto',
}}
>
//
</div>
方法2:
打印时 临时
修改样式,打印后恢复
原来样式,但是,页面太大超出了屏幕可视区域,还是打印不全:
使用 scrollX 和 scrollY 选项
html2canvas 提供了一些选项来控制截取行为,包括 scrollX 和 scrollY。这些选项可以用于截取页面上的所有内容,而不仅仅是当前可视区域。
核心
scrollX: 0, // 水平滚动位置
scrollY: 0, // 垂直滚动位置
width: inputRef.current.scrollWidth, // 截取的宽度
height: 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', // 背景颜色(如果需要透明背景)
});