根据 API 响应在组件内渲染 PDF 文件

问题描述 投票:0回答:2

我有一个返回 File(byte[], "application/pdf") | 的 API 来自服务器的字节[]

在前端部分,我创建一个请求,并且可以像 pdf 文件一样将此文件保存到计算机上,但是我需要 存储此文件(状态或其他方式)并像 PDF 文件一样在 React 组件中渲染,它可以放在 iframe 或其他方式上(对我来说这并不重要,只需要在从 API 获取文件后在组件内部渲染即可)。

 const instance = axios.create({
  baseURL: process.env.REACT_APP_API_ROOT,
  headers: {
    "Content-Type": "application/json",
  },
});

    function getPdfByFileName(fileName: string): any {
  return instance.get(`pdfs/${fileName}`);
}

function getPdfAsBlobByFileName(fileName: string): any {
  return instance.get(`pdfs/${fileName}/array`);
}

 useEffect(() => {
      getPdfByFileName("fileName")
        .then((response: AxiosResponse) => {
          // const file = new Blob([response.data], { type: "application/pdf" }); // For  API which returns blob
          setPdf(response.data); // Need store file and correct render like PDF
        })
        .catch((err: AxiosError) => {
         // process err
        });
    }
  }, []);

     return (
    <div>
      <iframe title="pdf" width="100%" height="600px" srcDoc={pdf}></iframe>
    </div>
  );

结果:Inside component I render the data but it's no PDF

我已经尽力了:

  1. 在这些请求中使用“Content-Type”:“application/pdf”。
  2. 将文件的 URL 放入 Iframe src 属性中(它适用于 匿名,但我们有承载并且需要保护数据)。
  3. 从 blob API 响应生成 URL 并放入 Iframe(不起作用)。
  4. 不同的 pdf 查看器,它们可以根据文件路径很好地处理物理 PDF 文件,但在我的情况下不起作用。

感谢您的帮助。

javascript reactjs pdf axios pdf-generation
2个回答
2
投票

对我来说,问题出在 axios 上,响应不正确,我只是切换到使用 fetch 方法,然后这种情况开始对我来说正确,与 axios 一样对我不起作用

    const request = new Request(`URL_TO_API`,
            {
              method: "GET",
              headers: {
                Authorization: `Bearer ${accessToken}`,
              },
              mode: "cors",
              cache: "default",
            }
          );
    
          fetch(request)
            .then((response) => response.blob())
            .then((blob) => {              
              const file = window.URL.createObjectURL(blob);
              const iframe = document.querySelector("iframe");
              if (iframe?.src) iframe.src = file;
            })
            .catch((err: AxiosError) => {
              // process error
            });
return (        
    <div>
      <iframe src="" width="100%" height="100%"></iframe>
    </div>
  );

0
投票

尝试一下它在我的应用程序中的工作

© www.soinside.com 2019 - 2024. All rights reserved.