| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- <template>
- <div>
- <canvas class="pdf pdf-canvas" id="pdf-canvas" :class="classList"></canvas>
- <div v-if="loading" class="loading">加载中...</div>
- </div>
- </template>
- <script>
- import pdfjs from '@/utils/pdf'
- import downloadFile from '@/utils/download-base64'
- import { mapState } from 'vuex'
- import { SET_TOTAL_PAGES, USE_SCREEN_SHOT } from '@/store/types/pdf-types'
- export default {
- data () {
- return {
- loading: true
- }
- },
- mounted () {
- this.loading = true
- this._canvas = document.getElementById('pdf-canvas')
- this._context = this._canvas.getContext('2d')
- // Default size
- this._canvas.height = 1080
- this._canvas.width = 1440
- if (this.src) {
- this.load(this.src)
- } else {
- // ! 1秒后重试
- setTimeout(() => {
- this.load(this.src)
- }, 1000)
- }
- },
- computed: {
- ...mapState({
- src: state => state.pdf.src,
- showDiscussion: state => state.pdf.showDiscussion,
- currentPage: state => state.pdf.currentPage,
- screenShot: state => state.pdf.screenShot
- }),
- classList () {
- return {
- 'full-size': !this.showDiscussion
- }
- }
- },
- watch: {
- currentPage () {
- this.showPage()
- },
- screenShot () {
- if (this.screenShot) {
- this.getScreenShot()
- this.$store.commit(USE_SCREEN_SHOT)
- }
- }
- },
- methods: {
- load (src) {
- const loadingTask = pdfjs.getDocument(src)
- loadingTask.promise.then(pdf => {
- this.loading = false
- this._pdf = pdf
- this.$store.commit(SET_TOTAL_PAGES, { totalPages: pdf.numPages })
- this.showPage()
- })
- },
- showPage () {
- this._pdf && this._pdf.getPage(this.currentPage || 1).then(page => {
- const scale = 2.5
- const viewport = page.getViewport({ scale: scale })
- this._canvas.height = viewport.height
- this._canvas.width = viewport.width
- const renderContext = {
- canvasContext: this._context,
- viewport: viewport
- }
- page.render(renderContext)
- }).catch(() => {
- this.$setInfoMessage('PDF 当前页解析错误')
- })
- },
- getScreenShot () {
- const img = this._canvas.toDataURL('image/png')
- downloadFile(img, '课程课件截图.png')
- }
- }
- }
- </script>
- <style lang="scss" scoped>
- @import '~@/style/theme.scss';
- div {
- position: relative;
- }
- .loading {
- position: absolute;
- display: flex;
- align-items: center;
- justify-content: center;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- color: #7a8a9a;
- font-size: 40px;
- }
- canvas {
- outline: none;
- display: block;
- direction: ltr;
- margin: 0 auto;
- background-color: white;
- max-width: 100vw;
- max-height: 100vh;
- }
- </style>
|