React使用Axios获取API返回PDF后直接打开打印窗口的实现咨询
解决方案
方案1:原生实现(无需引入第三方库)
核心思路是通过Axios请求拿到PDF二进制流,生成临时Blob地址后用隐藏iframe加载PDF,触发浏览器打印能力。
示例代码
import axios from 'axios'; const printPdfFromApi = async () => { try { // 注意必须配置responseType为blob,否则会拿到乱码文本 const response = await axios.get('替换为你的API地址', { responseType: 'blob' }); // 手动指定Blob类型为pdf,适配你接口返回的application/download格式 const pdfBlob = new Blob([response.data], { type: 'application/pdf' }); const pdfTempUrl = URL.createObjectURL(pdfBlob); // 创建隐藏的iframe用于加载打印内容 const printIframe = document.createElement('iframe'); printIframe.style.cssText = 'position: absolute; width: 0; height: 0; border: none; opacity: 0;'; printIframe.src = pdfTempUrl; document.body.appendChild(printIframe); // iframe加载完成后触发打印 printIframe.onload = () => { printIframe.contentWindow.focus(); printIframe.contentWindow.print(); // 打印完成后清理临时资源,避免内存泄漏 setTimeout(() => { document.body.removeChild(printIframe); URL.revokeObjectURL(pdfTempUrl); }, 100); }; } catch (error) { console.error('PDF打印失败:', error); } };
方案2:第三方库实现(兼容性更强)
如果需要适配更多浏览器的打印行为差异,可使用print-js库简化开发。
操作步骤
- 安装依赖
npm install print-js
- 业务代码实现
import axios from 'axios'; import printJS from 'print-js'; const printPdfFromApi = async () => { try { const response = await axios.get('替换为你的API地址', { responseType: 'blob' }); const pdfBlob = new Blob([response.data], { type: 'application/pdf' }); const pdfTempUrl = URL.createObjectURL(pdfBlob); printJS({ printable: pdfTempUrl, type: 'pdf', // 打印弹窗关闭后清理资源 onPrintDialogClose: () => { URL.revokeObjectURL(pdfTempUrl); } }); } catch (error) { console.error('PDF打印失败:', error); } };
内容的提问来源于stack exchange,提问作者Pradip Vadher
相关产品推荐
相关产品推荐

