Two ways to preview and print PDF in Vue3

Project scenario: The background interface requests data, returns a link to the PDF document, and can preview and print the PDF on the vue3 page.

In the previous Vue2 project, the vue-pdf plug-in was used to preview and print PDF, but it is not supported in vue3, so you can only change the plug-in, so after testing, I stepped on some pits and summarized the following two method:

Method 1: Use vue-pdf-embed  pdfjs-dist

① First, install these two plug-in dependencies

pnpm install vue-pdf-embed
pnpm install pdfjs-dist2.0.943

At that time, I encountered a problem when installing pdfjs-dist. I did not specify the version number, and the console reported an error. After reading some articles, some bloggers suggested installing version 2.0.943, so I re-entered the command and installed this version. Normal

②Write relevant codes on the page

// 引入插件
import VuePdfEmbed from 'vue-pdf-embed'
import * as pdfjsLib from 'pdfjs-dist'
//定义
const state = reactive({
    source: '', // 预览pdf文件地址
    pageNum: 0, // 当前页面
    scale: 1, // 缩放比例
    numPages: 0 // 总页数
})
const scale = computed(() => `transform:scale(${state.scale})`)
<div>
      // 操作按钮
      <div class="page-tool">
        <div class="page-tool-item" @click="lastPage">上一页</div>
        <div class="page-tool-item" @click="nextPage">下一页</div>
        <div class="page-tool-item">{
   
   { state.pageNum }}/{
   
   { state.numPages }}</div>
        <div class="page-tool-item" @click="pageZoomOut">放大</div>
        <div class="page-tool-item" @click="pageZoomIn">缩小</div>
     </div>
     //pdf预览
     <vue-pdf-embed ref='pdf' :source="state.source" :style="scale" :page="state.pageNum" class="vue-pdf-embed" />
 </div>
<script setup>
    onMounted(()=>{
        getPdfUrl(pdfUrl)  // pdfUrl即url地址链接
    })
    function getPdfUrl(data){
        state.source = data
        pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
        const loadingTask = pdfjsLib.getDocument(data)
        loadingTask.promise.then(pdf => {
            state.numPages = pdf.numPages
        })
    }
    // 上一页
    function lastPage() {
        if (state.pageNum > 1) {
            state.pageNum -= 1
        }
    }
    // 下一页
    function nextPage() {
        if (state.pageNum < state.numPages) {
            state.pageNum += 1
        }
    }
    // 放大
    function pageZoomOut() {
        if (state.scale < 2) {
            state.scale += 0.1
        }
    }
    // 缩小
    function pageZoomIn() {
        if (state.scale > 1) {
            state.scale -= 0.1
        }
    }
</script>

In order to look better, I wrote a style for the action button

<style lang="scss" scoped>
    .page-tool {
        display: flex;
        position: absolute;
        top: 5px;
        left: 50%;
        z-index: 100;
        transform: translateX(-50%);
        align-items: center;
        background: rgb(66 66 66);
        color: white;
        border-radius: 19px;
        cursor: pointer;
        justify-content: center;
        font-size: 15px;
    }
    .page-tool-item {
        padding: 4px 10px;
        cursor: pointer;
    }
</style>

 The final realization effect:

Print:

const { proxy } = getCurrentInstance()

<div @click='print'>打印</div>
<script setup>
    function print(){
        proxy.$refs['pdf'].print()
    }
</script>

 Method 2: Use pdfjs-dist, canvas rendering, pdf.js printing

  Description: pdf.js can print canvas data, so choose this plugin

① First, install dependencies

pnpm install pdfjs-dist

 After installation, in the node_modules folder of the project, find the pdfjs-dist ->build->pdf.worker.js file, copy it out and put it in the public root directory, then find the pdfjs-dist ->cmaps folder, copy it and put it Go to the public->static folder, as shown below:

②Download print.js and put it into the project, introduce the method on the page that needs to be used, and then call the method

Specifically, I refer to this blog post: Front-end printing using print.js_printjs_@我不知道你的博客-CSDN Blog

③ Code implementation

// 打印按钮
<div @click="print">打印</div> 

//pdf预览显示
<div>
    <div id="printDom" ref="printDom">
        <div v-for="item in state.numPages" :key="item">
            <canvas :id="`pdfCanvas-${item}`" :ref="`pdfCanvas-${item}`" />
        </div>
    </div>
</div>

<script setup>
    import * as pdfjsLib from 'pdfjs-dist' //引入pdfjs-dist
    import Print from '@/assets/js/print'  //引入print.js
    const { proxy } = getCurrentInstance()
    const state = reactive({
        source: '', // 预览pdf文件地址
        pageNum: 0, // 当前页面
        scale: 1, // 缩放比例
        numPages: 0, // 总页数
        pdfCtx: null // pdf对象
    })
    onMounted(()=>{
        pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
        const loadingTask = pdfjsLib.getDocument({
            url: pdfUrl,  //这里的pdfUrl即pdf的链接地址
            cMapUrl: '../../../../static/cmaps/',
            cMapPacked: true
        })
        loadingTask.promise.then(pdf => {
            // console.log('页数', pdf.numPages)
            state.numPages = pdf.numPages
            state.pdfCtx = pdf
            nextTick(() => {
                renderPdf()
            })
        })
    })
    const renderPdf = (num = 1) => {
        state.pdfCtx.getPage(num).then(page => {
            const canvas = document.getElementById(`pdfCanvas-${num}`)
            const ctx = canvas.getContext('2d')
            const viewport = page.getViewport(1.6)
            canvas.height = viewport.height
            canvas.width = viewport.width
            page.render({
                canvasContext: ctx,
                viewport: viewport
            })
            if (num < state.numPages) {
                renderPdf(num + 1)
            }
        })
    }
    //打印
    function print(){
        Print(proxy.$refs['printDom'])
    }
</script>

Guess you like

Origin blog.csdn.net/qing_jian0119/article/details/128739730