使用react-pdf从reactJS渲染静态PDF

时间:2017-10-20 22:52:16

标签: reactjs pdf

这是我的代码。 Webpack正好加载PDF。反应组件不呈现pdf。当通过react组件访问时,它会显示一个带有页面号的空白页面。 1的 将以下网址放入浏览器时,它会直接从浏览器呈现pdf,并且没问题。

http://localhost:3000/bfa955d1b47a762fb2b4d8cc2525f637.pdf

import React, {Component} from "react";
import myPdf from '../images/BSOAANZChapterConstitution.pdf'
import {Document, Page} from 'react-pdf/build/entry.webpack';

class Constitution extends Component {
    constructor(props) {
        super(props);
        this.state = {
            numPages: null,
            pageNumber: 1
        };
    }

    onDocumentLoad({numPages}) {
        this.setState({numPages});
    }

    render() {

        const {pageNumber, numPages} = this.setState;
        return (
            <div>
                <Document
                    file={myPdf} onLoadSuccess={this.onDocumentLoad}>
                    <Page pageNumber={pageNumber}/>
                </Document>
                <p>Page {pageNumber} of {numPages}</p>
            </div>
        );
    }
}

export default Constitution;

2 个答案:

答案 0 :(得分:1)

我认为问题仅仅是因为没有将this.onDocumentLoad事件处理程序绑定到this。如果要从事件处理程序访问属性,状态和组件方法(如setState),则需要将该处理程序绑定到this。因此,在构造函数中添加以下内容。

this.onDocumentLoad = this.onDocumentLoad.bind(this)

答案 1 :(得分:0)

I added the line mentioned in the above suggestion. It dint work. I tried a few other packages too, they din't work. It was the same problem, no errors but pdf was not being loaded.
I got it working now by using react-pdf-js-infinite, I am not sure if it also allows navigation controls and page numbers. But so far, it at least renders the pdf.

react-pdf-infinite Code was just one import and file specification.

class Constitution extends Component {
   render() {
        return (
            <PDF file={myPdf} scale={1.5} />
        );
    }
}

export default Constitution;