使用printJS在Safari浏览器打印Base64转PDF时出现空白问题求助
解决Safari中printJS打印Base64 PDF空白的问题
针对你在Safari浏览器中使用printJS打印Base64格式PDF时,打印窗口空白无内容(Chrome中正常)的问题,以下是几个经过验证的修复方案:
方案1:手动转换Base64为Blob并通过iframe加载打印
Safari对printJS原生的Base64 PDF处理支持存在缺陷,可手动将Base64数据转换为Blob对象,再通过隐藏iframe加载后触发打印:
function printBase64PDF(base64Data) { // 移除Base64前缀(如果数据自带的话) const pureBase64 = base64Data.replace(/^data:application\/pdf;base64,/, ''); // 解码Base64为字节数组 const byteChars = atob(pureBase64); const byteArray = new Uint8Array(byteChars.length); for (let i = 0; i < byteChars.length; i++) { byteArray[i] = byteChars.charCodeAt(i); } // 创建PDF Blob对象 const pdfBlob = new Blob([byteArray], { type: 'application/pdf' }); const blobUrl = URL.createObjectURL(pdfBlob); // 创建隐藏iframe加载PDF const iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = blobUrl; document.body.appendChild(iframe); // 加载完成后触发打印,打印后清理资源 iframe.onload = function() { setTimeout(() => { iframe.contentWindow.print(); setTimeout(() => { URL.revokeObjectURL(blobUrl); document.body.removeChild(iframe); }, 1000); }, 500); }; } // 调用示例 printBase64PDF(samplebase64response);
方案2:通过新窗口加载PDF后打印
如果iframe方式仍有问题,可改用新窗口加载Blob URL,再触发打印操作:
function printBase64PDF(base64Data) { const pureBase64 = base64Data.replace(/^data:application\/pdf;base64,/, ''); const byteChars = atob(pureBase64); const byteArray = new Uint8Array([...byteChars].map(char => char.charCodeAt(0))); const pdfBlob = new Blob([byteArray], { type: 'application/pdf' }); const blobUrl = URL.createObjectURL(pdfBlob); const printWindow = window.open(blobUrl, '_blank'); printWindow.onload = function() { printWindow.print(); // 延迟清理资源,避免打印流程中断 setTimeout(() => { URL.revokeObjectURL(blobUrl); printWindow.close(); }, 2000); }; }
方案3:检查Base64数据有效性
确认你的samplebase64response数据格式正确:
- 确保数据带有
data:application/pdf;base64,前缀(如果没有可手动添加) - 检查Base64字符串无换行、空格等无效字符
内容的提问来源于stack exchange,提问作者PRITAM DEBNATH
相关产品推荐
相关产品推荐

