天天看點

vue3中使用pdfjs-dist預覽pdf,vue.config.js配置pdf檔案

參考博文:

1.pdfjs-dist        https://juejin.cn/post/6995856687106261000

2.vue.config.js配置    https://ask.csdn.net/questions/7425984

遇到問題:

1.vue-pdf在vue3項目中引入時報錯,似乎是不支援。是以選擇了pdfjs-dist。

2.在引入pdf檔案時報錯

vue3中使用pdfjs-dist預覽pdf,vue.config.js配置pdf檔案

 解決:配置vue.config.js中對pdf檔案的支援。

const path = require('path');

module.exports = {

    publicPath: "./", // 建構好的檔案輸出到哪裡

    outputDir: "dist", // where to put static assets (js/css/img/font/...) // 是否在儲存時使用‘eslint-loader’進行檢查 // 有效值: true | false | 'error' // 當設定為‘error’時,檢查出的錯誤會觸發編譯失敗

    assetsDir: 'assets',

    transpileDependencies:['@vue/reactivity'],

    chainWebpack: config => {
        // ...
        config.module.rule('pdfjs-dist').test({
         test: /\.js$/,
         include: path.join(__dirname, 'node_modules/pdfjs-dist')
       }).use('babel-loader').loader('babel-loader').options({
         presets: ['@babel/preset-env'],
         plugins: ['@babel/plugin-proposal-optional-chaining']
       })

//-------------------------- 配置pdf檔案----------------------------------------
       config.module
       .rule('pdf')
       .test(/\.(pdf)$/)
       .use('url-loader')
       .loader('url-loader')
       .options({
         limit: 10000
       })
       .end()
//-------------------------- 配置pdf檔案----------------------------------------
     },
};
           

3.注意:

需要在引入

pdfjs-dist

之後配置

workerSrc

,但是引入

pdfjs-dist/build/pdf.worker.entry

之後浏覽器還是有個警告:

Warning: Setting up fake worker.

,經過各種原因查找,最終找到了一句描述:pdf.worker.js必須位于自己的檔案中(而不是與pdf.js捆綁在一起)。否則它不能在服務工作線程中運作。

解決方式:将

pdfjs-dist/build/pdf.worker.js

複制一份放到項目

public

目錄下。

以下是元件全部代碼:

<template>
    <div class="help-page">
        <template v-for="item in pageNum" :key="item">
            <canvas :id="`pdf-canvas-${item}`" class="pdf-page" />
        </template>
        <canvas id="pdf-canvas" class="pdf-page" />
    </div>
</template>

<script >
import { defineComponent, toRefs, nextTick, reactive } from '@vue/runtime-core'
/**
 * 幫助文檔:HelpPage
 * ==========================================
 */
export default defineComponent({
    code: '幫助文檔',
    name: 'HelpPage',
    props: {},
    components: {},
    setup() {
        const PDF = require('pdfjs-dist')
        const url = require('../../../public/help.pdf')
        PDF.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'

        const state = reactive({
            pageNum: 0,
            pdfCtx: null,
        })

        const resolvePdf = () => {
            const loadingTask = PDF.getDocument(url)
            loadingTask.promise.then((pdf: any) => {
                state.pdfCtx = pdf
                state.pageNum = pdf.numPages
                nextTick(() => {
                    renderPdf()
                })
            })
        }
        const renderPdf = (num = 1) => {
            if (state.pdfCtx) {
                const pdfCtx = state.pdfCtx as any
                pdfCtx.getPage(num).then((page: any) => {
                    const canvas = document.getElementById(
                        `pdf-canvas-${num}`
                    ) as any
                    const ctx = canvas.getContext('2d')
                    const viewport = page.getViewport({ scale: 2 })
                    var CSS_UNITS = 96.0 / 72.0
                    canvas.height = Math.floor(viewport.height * CSS_UNITS)
                    canvas.width = Math.floor(viewport.width * CSS_UNITS)
                    // 畫布的dom大小, 設定移動端,寬度設定鋪滿整個螢幕
                    const clientWidth = canvas.width
                    canvas.style.width = clientWidth + 'px'
                    // 根據pdf每頁的寬高比例設定canvas的高度
                    canvas.style.height =
                        clientWidth * (canvas.height / canvas.width) + 'px'
                    page.render({
                        transform: [CSS_UNITS, 0, 0, CSS_UNITS, 0, 0],
                        canvasContext: ctx,
                        viewport,
                    })
                    if (num < state.pageNum) {
                        renderPdf(num + 1)
                    }
                })
            }
        }

        resolvePdf()

        return { PDF, ...toRefs(state), resolvePdf, renderPdf }
    },
})
</script>

<style  scoped>
.help-page {
    width: 100%;
    height: 100%;
}
</style>
           

繼續閱讀