【问题标题】:How to open a pdf in new tab in reactjs?如何在reactjs的新标签中打开pdf?
【发布时间】:2017-05-24 12:46:56
【问题描述】:

我们将 pdf 文档保存在数据库中,来自 webapi 我是 作为字节数组返回,现在从 UI 我必须在新选项卡中打开 pdf 浏览器,用户应该能够下载pdf。我怎样才能 实现这个打开和下载pdf文档的需求?

【问题讨论】:

  • 看看这篇文章:stackoverflow.com/questions/41504668/… 有一些答案,似乎答案可能在 React 模块 react-pdf 或 react-pdfjs 中
  • @Jayce444 我也这样做了,但问题是我们无法下载打开的 pdf。如果您右键单击,它将保存为图像。但我的要求是下载打开的 pdf。
  • @Jayce444 你有什么更好的解决方案吗?

标签: arrays reactjs asp.net-web-api react-redux


【解决方案1】:

你可以这样使用:

<a href='/api/v1/print/example.pdf' target='_blank' rel='noopener noreferrer'>

【讨论】:

  • 我试过 window.open(this.state.path, "_blank");但它在路径正确时无法识别路径:无法获取 /Decoding.pdf 并且在浏览器中加载资源失败:服务器响应状态为 404(未找到)错误即将到来
  • @jack 你能写出路径包含什么吗?
【解决方案2】:

以下代码对我有用

try {
    await axios
      .get(uri.ApiBaseUrl + "AccountReport/GetTrialBalancePdfReport", {
        responseType: "blob",
        params: {
          ...searchObject,
        },
      })
      .then((response) => {
        //Create a Blob from the PDF Stream
        const file = new Blob([response.data], { type: "application/pdf" });
        //Build a URL from the file
        const fileURL = URL.createObjectURL(file);
        //Open the URL on new Window
         const pdfWindow = window.open();
         pdfWindow.location.href = fileURL;            
      })
      .catch((error) => {
        console.log(error);
      });
  } catch (error) {
    return { error };
  }

【讨论】:

  • 感谢。但请记住,它不适用于 Safari。
【解决方案3】:

2020 年的解决方案

   import Pdf from '../Documents/Document.pdf';

   <a href={Pdf} without rel="noopener noreferrer" target="_blank">
      <button trailingIcon="picture_as_pdf" label="Resume">
        PDF
      </button>
   </a>

【讨论】:

  • 谢谢。唯一对我有用的解决方案。唯一真正使用本地文件中的 PDF 的解决方案
  • 太好了,很高兴它可以帮助你@Alexander
猜你喜欢
  • 1970-01-01
  • 2014-03-26
  • 2017-05-21
  • 2018-11-05
  • 1970-01-01
  • 2016-10-21
  • 2022-01-16
  • 2020-05-31
  • 2017-01-24
相关资源
最近更新 更多