【pdfjs+vue】vue中实现pdf预览并且内容可复制,点击内容链接可页面跳转

使用pdfjs插件,在vue中实现pdf预览,内容可复制,点击内容链接可以实现页面跳转功能。

1.安装pdfjs

npm install pdfjs-dist@2.0.943

2.在组件中引入pdfjs

  // pdfjs 2.0.943 资源引入
    import * as pdfjsLib from 'pdfjs-dist';
    import { workerSrc } from "pdfjs-dist/build/pdf.worker.min";
    pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;
    import { TextLayerBuilder } from 'pdfjs-dist/web/pdf_viewer';
    import 'pdfjs-dist/web/pdf_viewer.css';

3.完整代码

<template>
    <div>
        <h1>PDF渲染</h1>
        <button @click="pdfPrint()">打印</button>
        <div id="pdfBox" style="min-height: 500px;"></div>
    </div>
</template>
<script>
// pdfjs 2.0.943 资源引入
import * as pdfjsLib from 'pdfjs-dist';
import { workerSrc } from "pdfjs-dist/build/pdf.worker.min";
pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;
import { TextLayerBuilder } from 'pdfjs-dist/web/pdf_viewer';
import 'pdfjs-dist/web/pdf_viewer.css';
export default {
    data() {
        return {
            pdf: ''
        }
    },
    methods: {
        //打印
        pdfPrint(){
            window.print();
        },

        // 在 PDF 页面上叠加超链接
        addLinkToPage(page, link) {
            console.log("link===", link);
            const linkDiv = document.createElement("a");
            linkDiv.href = link.url;
            linkDiv.target = "_blank";
            linkDiv.style.position = "absolute";
            linkDiv.style.left = link.rect[0] * 1.5 + "px";
            linkDiv.style.top = (843 - link.rect[3]) * 1.5 + "px";
            linkDiv.style.width = (link.rect[2] - link.rect[0]) * 1.5 + "px";
            linkDiv.style.height = (link.rect[3] - link.rect[1]) * 1.5 + "px";
            linkDiv.style.backgroundColor = "transparent";
            // linkDiv.style.border = "1px solid red";
            linkDiv.style.pointerEvents = "auto";
            linkDiv.style.zIndex = "1"
            page.appendChild(linkDiv);
        },

        /**
         * 渲染每页pdf
         */
        renderPage(pageNumber) {
            this.pdf.getPage(pageNumber).then((page) => {
                // var viewport = page.getViewport({ scale: 1.5 });
                var viewport = page.getViewport(1.5);

                // 创建canvas承载pdf内容
                const canvas = document.createElement("canvas");
                const canvasContext = canvas.getContext("2d");
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                canvas.style.display = "block";

                canvasContext.setTransform(1, 0, 0, 1, 0, 0);

                const canvasBox = document.createElement("div");
                canvasBox.style.height = viewport.height + 2 + "px";
                canvasBox.style.width = viewport.width + 2 + "px";
                canvasBox.style.margin = "0 auto 10px";
                canvasBox.style.border = "1px solid #ccc";
                canvasBox.style.position = "relative";
                canvasBox.appendChild(canvas);

                const pdfBox = document.getElementById("pdfBox");
                pdfBox.appendChild(canvasBox);

                const renderContext = {
                    canvasContext,
                    viewport,
                };

                page
                    .render(renderContext)
                    .then(() => {
                        return page.getTextContent();
                    })
                    .then((textContent) => {
                        // 实现选中复制功能
                        const textLayerDiv = document.createElement("div");
                        textLayerDiv.setAttribute("class", "textLayer");
                        canvasBox.appendChild(textLayerDiv);

                        let textLayer = new TextLayerBuilder({
                            textLayerDiv: textLayerDiv,
                            pageIndex: page.pageIndex,
                            viewport: viewport,
                        });

                        textLayer.setTextContent(textContent);
                        textLayer.render();
                    });

                // 实现链接点击
                page.getAnnotations().then(function (annotations) {
                    console.log("annotations==", annotations);
                    annotations.forEach(function (annotation) {
                        if (annotation.subtype === "Link") {
                            this.addLinkToPage(canvasBox, annotation);
                        }
                    });
                });
            });
        },
    },
    mounted() {
        // 本地渲染pdf, 避免浏览器获取iframe高度各种兼容性问题
        //这里获取线上PDF地址,测试暂时写死
        const url = 'xxx';
        pdfjsLib.getDocument(url).promise.then((pdf) => {
            this.pdf = pdf;
            let pages = pdf.numPages;
            for (let i = 1; i <= pages; i++) {
                this.renderPage(i);
            }
        });
    }
}
</script>
Vue3 中,处理 PDF 组件的用户交互通常涉及到使用第三方库,如 vue-pdfpdfjs-dist。以下是基本步骤: 1. 安装库:首先安装一个适合 VuePDF 阅读库,例如 `vue-pdf`: ``` npm install vue-pdf pdfjs-dist ``` 2. 在组件中引入和配置 PDF: ```html <template> <div> <pdf :src="pdfSrc" @page-loaded="onPageLoad"></pdf> </div> </template> <script> import { Pdf } from 'vue-pdf' export default { components: { Pdf }, data() { return { pdfSrc: 'path/to/your/pdf/file.pdf', } }, methods: { onPageLoad({ num }) { // num 参数表示当前加载的页面编号 this.currentPage = num // 添加点击监听器,这里假设有个变量 currentPageClickHandler 存储了点击事件处理器 this.currentPageClickHandler(num) }, }, } </script> ``` 3. 实现 `currentPageClickHandler` 方法,以便处理点击事件并获取点击页码及详细信息。这通常需要结合 PDF.js 库提供的 API,例如 `getAnnotations` 获取注释、链接等: ```javascript methods: { currentPageClickHandler(pageNum) { // 使用 pdfjsDist 加载 PDF 并获取当前页面的注解 PDFJS.getDocument(this.pdfSrc).promise.then((doc) => { doc.getPage(pageNum).then((page) => { const annotations = page.getAnnotations(); // 根据注解类型(比如链接、形状)解析详细信息 // 示例:查找包含链接的注解 annotations.forEach((annotation) => { if (annotation instanceof PDFLinkAnnotation) { console.log('Clicked on link at page:', pageNum, ', annotation:', annotation); // 在这里你可以获取更详细的链接属性或其他信息 } }); }); }); }, }, ``` 4. 当然,你需要根据实际需求自定义注解的处理逻辑,可能包括跳转、显示提示信息等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值