vue3中使用pdfjs-dist预览pdf,vue.config.js配置pdf文件

4 篇文章 0 订阅
参考博文:1.pdfjs-dist https://juejin.cn/post/69958566871062610002.vue.config.js配置 https://ask.csdn.net/questions/7425984遇到问题:1.vue-pdf在vue3项目中引入时报错,似乎是不支持。所以选择了pdfjs-dist。2.在引入pdf文件时报错解决:配置vue.config.js中对pdf文件的支持。const path = requir...
摘要由CSDN通过智能技术生成

参考博文:

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

2.vue.config.js配置    vue.config.js里面test(/\.(JPG|PNG)$/)小写的时候jpg图片不显示_前端-CSDN问答

遇到问题:

1.vue-pdf在vue3项目中引入时报错,似乎是不支持。所以选择了pdfjs-dist。

2.在引入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 lang="ts">
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 lang="scss" scoped>
.help-page {
    width: 100%;
    height: 100%;
}
</style>

  • 8
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值