如何在reactjs中打开pdf?

IT技术 reactjs react-redux
2021-05-27 09:05:33

对于 web api,我将 pdf 返回为:-

[EnableCors("*", "*", "*")]
[HttpGet]
public byte[] GetReportData()
{
 string filePath = "D:\\Decoding.pdf";
 byte[] bytes = File.ReadAllBytes(filePath);
 return bytes;
}

我在我的操作和减速器中调用该方法为:-

行动:-

export  function LoadReportData () {
    return (dispatch) => {
    dispatch({
      type: REQUEST_REPORT,//defining the name of the action to identify in the reducer
    });

    fetch(APIPATH+'Requisition/GetReportData')//calling the service
    .then((response) => response.json())
    .then((report) => dispatch(receiveReport(report)));//passing the data to other actions
  }
}


//this method use to pass the data coming for the lab test result to the component
export  function receiveReport(report) {

  return {
    type:RECEIVE_REPORT,//defining the name of the action to identify in the reducer
    report:report//passing the data to reducer
  };
}

减速机:-

case  'RECEIVE_REPORT':
        return Object.assign({}, state, {
          report: action.report,
          loadingReport: false,
        });
    case 'REQUEST_REPORT':
        return Object.assign({}, state, {
          loadingReport: true
        });

现在,当我从 web api 传递时,报告以字节的形式出现。现在我的要求是如何在我的组件或浏览器的下一个选项卡中显示这个来自 web api 的字节数组的 pdf 文件? 注意:报告包含字节数组

3个回答

您必须使用 pdfbox 可作为 jar 打开 pdf 文件

我正在发布我的代码,这对我来说很好用:-

import React,{Component} from 'react'
import ReactDOM from "react-dom";
import PDF from "react-pdfjs";
class PreviewComponent extends Component{
 constructor(props) {
    super(props);
    this.state={
      reportData:this.props.reportData,
      page:1,
      scale:1.0
    }
   this.onDocumentCompleted=this._onDocumentCompleted.bind(this);
     this.onPageCompleted=this._onPageCompleted.bind(this);
  }

 render() {
        return <PDF content={this.state.reportData} page={this.state.page} scale={this.state.scale} onDocumentComplete={this._onDocumentComplete} onPageComplete={this._onPageComplete} loading={(<span>Your own loading message ...</span>)} />
  }
  _onDocumentCompleted(pages){
    this.setState({pages: pages});
  }
  _onPageCompleted(page){
    this.setState({currentPage: page});
  }
}
export default PreviewComponent;

你应该安装react-pdf

Install with npm install react-pdf

在您的应用中使用:

var PDF = require('react-pdf');

var MyApp = React.createClass({
  render() {

    return '<PDF content="YSBzaW1wbGUgcGRm..." page="1" scale="1.0" onDocumentComplete={this._onDocumentComplete} onPageComplete={this._onPageComplete} loading={(<span>Your own loading message ...</span>)} />';
  },
  _onDocumentCompleted(pages){
    this.setState({pages});
  },
  _onPageCompleted(page){
    this.setState({currentPage: page});
  }
});