32 lines
2.0 KiB
JavaScript
32 lines
2.0 KiB
JavaScript
'use strict';
|
|
(()=>{
|
|
const button=document.getElementById('print'),frame=document.querySelector('.print-frame'),content=document.querySelector('.content'),status=document.getElementById('fit-status');
|
|
// 先压缩空行与行距,再根据真实排版尺寸缩放;保留每个商品及附加项,不裁掉尾部。
|
|
function fit(){
|
|
try{
|
|
content.style.transform='none';content.style.width='100%';content.classList.remove('compact');
|
|
if(content.scrollHeight>frame.clientHeight)content.classList.add('compact');
|
|
if(!content.scrollHeight||!frame.clientWidth||!frame.clientHeight)throw new Error('页面尺寸未就绪');
|
|
const availableWidth=frame.clientWidth-1,availableHeight=frame.clientHeight-1;
|
|
const measure=scale=>{
|
|
content.style.width=(availableWidth/scale)+'px';
|
|
return Math.max(content.scrollHeight,content.offsetHeight)*scale<=availableHeight&&Math.max(content.scrollWidth,content.offsetWidth)*scale<=availableWidth+1;
|
|
};
|
|
let scale=1;
|
|
if(!measure(1)){
|
|
let low=.0001,high=1;
|
|
if(!measure(low))throw new Error('内容超出纸张可用范围');
|
|
for(let i=0;i<18;i++){const mid=(low+high)/2;if(measure(mid))low=mid;else high=mid;}
|
|
scale=low;measure(scale);
|
|
}
|
|
content.style.transform='scale('+scale+')';content.dataset.scale=String(scale);
|
|
document.body.classList.remove('fit-error');button.disabled=false;
|
|
status.textContent=scale<.65?'已排为一页;内容较多,字号已缩小,请先查看预览。':'已排为一页,全部明细与注意事项完整保留。';
|
|
return true;
|
|
}catch{document.body.classList.add('fit-error');button.disabled=true;status.textContent='页面暂未排好,请刷新后再打印。';return false;}
|
|
}
|
|
const ready=()=>document.fonts?.ready||Promise.resolve();
|
|
ready().then(fit);window.addEventListener('load',fit);window.addEventListener('resize',fit);window.addEventListener('beforeprint',fit);
|
|
button.addEventListener('click',async()=>{await ready();if(fit())window.print();});
|
|
})();
|