Created
September 26, 2018 09:09
-
-
Save eirslett/0fd3eeef134364747b454689276f6bcc to your computer and use it in GitHub Desktop.
React component for previewing PDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component, PropTypes} from 'react'; | |
require('pdfjs-dist'); | |
export default | |
class PdfPreview extends Component { | |
static propTypes = { | |
file: PropTypes.object | |
}; | |
constructor(props) { | |
super(props); | |
this.state = { | |
width: 500, | |
height: 200 | |
}; | |
} | |
componentDidMount() { | |
console.log('PdfPreview did mount'); | |
const data = this.props.file.data; | |
PDFJS.getDocument(data) | |
.then((doc) => doc.getPage(1).then((page) => { | |
const unscaledViewport = page.getViewport(1); | |
const canvas = this.refs.pdfCanvas; | |
const scale = canvas.width / unscaledViewport.width; // Math.min((canvas.height / unscaledViewport.height), (canvas.width / unscaledViewport.width)); | |
const xOffset = 0; // (unscaledViewport.height - canvas.height) / 2; | |
const yOffset = 0; // (unscaledViewport.width - canvas.width) / 2; | |
const scaledViewport = new PDFJS.PageViewport(page.view, scale, 0, xOffset, -yOffset); | |
const scaledHeight = unscaledViewport.height * scale; | |
console.log('refs', this.refs); | |
const canvasContext = canvas.getContext('2d'); | |
canvas.height = scaledHeight; | |
this.renderCanvas = () => page.render({canvasContext, viewport: scaledViewport}).then(() => this.resizeSilently(scaledHeight)); | |
return this.renderCanvas(); | |
})).then((res) => console.log('rendered', res), (err) => console.error(err)); | |
} | |
shouldComponentUpdate(nextProps, nextState) { | |
return this.state.width !== nextState.width; | |
} | |
componentDidUpdate() { | |
this.renderCanvas(); | |
} | |
resizeSilently(newHeight) { | |
console.log('resize to', newHeight); | |
this.setState({height: newHeight}); | |
} | |
render() { | |
return ( | |
<div style={{width: '100%'}}> | |
<canvas ref="pdfCanvas" width={this.state.width} height={this.state.height} style={{border: '1px solid #eeeeee', display: 'block', userSelect: 'none', width: '100%'}} /> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment