You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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库简化开发。

操作步骤

  1. 安装依赖
npm install print-js
  1. 业务代码实现
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 06:42:02