兜兜零元 发表于 2025-4-8 17:19:33

Vue 项目利用 pdf.js 及 Elasticpdf 教程

摘要:本文章先容如安在 Vue 中利用 pdf.js 及基于 pdf.js 的批注开发包 Elasticpdf。简单 5 步可完成集成摆设,包罗数据的云端同步,示例代码美满且简单,文末有集成代码分享。
https://i-blog.csdnimg.cn/img_convert/7d48b7e37b46a02d58dd9dd444b828ea.png
1. 工具库先容与 Demo

1.1 代码包结构

ElasticPDF基于开源 pdf.js (Demo地址:https://mozilla.github.io/pdf.js/web/viewer.html),增长了多种开箱即用的 PDF 批注功能。代码包延续了 pdf.js-dist 独立且完全离线的结构风格,仅增长了用于支持批注的离线 Javascript 代码,与 pdf.js-dist 一样可以快速完美集成到任何可以运行Javascript, HTML, CSS 的项目环境中,在公网及内网环境下运行。
https://i-blog.csdnimg.cn/img_convert/581e5fc3007c1d5aaeb6048b2416677e.png
1.2 Elasticpdf 在线 Demo

根据不同的功能及预算需求,有两个版本的产物可供选择,两者仅在最终的批注保存阶段有区别,产物 Demo 地址如下:
① 批注合成版: https://demos.libertynlp.com/#/pdfjs-annotation
② 专业批注版: https://www.elasticpdf.com/demo
2. 移动至 Vue 项目

移动 pdf.js 或 Elasticpdf 代码包到 Vue 项目的 public 文件夹下。
https://i-blog.csdnimg.cn/img_convert/00a7b66c301c66d4327190878e3b15f3.png
pdf.js 乐成导入 Vue 快照
https://i-blog.csdnimg.cn/img_convert/f624c59be7d4bcf1a78112e8038614fd.png
3. 导入 viewer.html

① 通过 <iframe> 导入 elasticpdf 或 pdf.js 代码包中的 viewer.html 文件,注意路径不要写错。
<!-- elasticpdf 示例 -->
<iframe @load='initialPDFEditor()' id='elasticpdf-iframe' src="elasticpdf/web/viewer.html"
        frameborder="0" width="100%" height="700px"></iframe>

<!-- pdf.js 示例 -->
<iframe @load='initialPDFEditor()' id='elasticpdf-iframe' src="pdfjs-3.2/web/viewer.html"
        frameborder="0" width="100%" height="700px"></iframe>
② 将 web 文件夹下 viewer.js 中 defaultUrl 默认值置空,否则在第 ① 步中导入 viewer.html 时会默认加载 compressed.tracemonkey-pldi-09.pdf 文件,影响自定义加载文件的流程。Elasticpdf 代码包中的 viewer.js 已默认修改完成。
// 原 defaultUrl 默认值
defaultOptions.defaultUrl = {
value: "compressed.tracemonkey-pldi-09.pdf",
kind: OptionKind.VIEWER
};

// 置空后默认值
defaultOptions.defaultUrl = {
value: "",
kind: OptionKind.VIEWER
};
③ 在 Vue 页面中的 <iframe> onLoad() 函数下调用 initialApp() 函数,由于 pdf.js 和 elasticpdf 中的函数都是在 iframe 的作用域下,因此必须在 iframe load结束可获取 contentWindow 后再调用。
var elasticpdf_viewer = null;
function initialPDFEditor() {
        listenPDFEditorMessage();
        elasticpdf_viewer = document.getElementById('elasticpdf-iframe').contentWindow;
        console.log('elasticpdf_viewer', elasticpdf_viewer);
        var pdf_url="compressed.tracemonkey-pldi-09.pdf";
        elasticpdf_viewer.initialApp({
                'language': 'zh-cn', // 交互语言
                'pdf_url': pdf_url,
                'member_info': { //用户信息
                        'id': 'elasticpdf_id',
                        'name': 'elasticpdf',
                },
        });
}
       
// 监听 pdf 编辑等各种信息的回调
function listenPDFEditorMessage() {
        window.addEventListener('message', (e) => {
                if (e.data.source !== 'elasticpdf') {
                        return;
                }

                // pdf 加载结束的回调,可以在此处导入服务器上储存的批注文件
                if (e.data.function_name === 'pdfLoaded') {
                        console.log('PDF加载成功');
                        reloadData();
                }
        });
}
④ pdf.js 初始化函数如下,主要内容为调用 PDFViewerApplication.open() 打开传入的文档链接,并利用 loadPdf() 函数监听文档是否初始化结束,最后通过 postMessage 广播加载状态至 Vue 页面。
<script type='text/javascript'>
        //初始化函数
        function initialApp(paras) {
                var oriUrl=paras['pdf_url'];
                PDFViewerApplication.open(oriUrl);
                interval = setInterval('loadPdf()', 1000);
        }
       
        //监听文档是否初始化完成
        var interval = null;
        function loadPdf() {
                if (PDFViewerApplication.pdfDocument == null) {
                        console.info('Loading...');
                } else {
                        //文档初始化完成
                        console.log('PDF Load successfully');
                        clearInterval(interval);
                        //广播信息
                        postPDFData("pdfLoaded", '');
                }
        }
       
        //广播 pdf.js 操作状态信息
        function postPDFData(function_name,new_content){
                window.parent.postMessage({"type":0,"source":"elasticpdf",'function_name':function_name,"content":new_content},'*');
                window.postMessage({"type":0,"source":"elasticpdf",'function_name':function_name,"content":new_content},'*');
        }
</script>
⑤ 必要注意的是 pdf.js 端和存放 pdf 文件的都要支持跨域,否则会报 CORS 跨域错误。具体来说如果服务器是通过 Java 大概 Python 等步伐提供文档,则必要在步伐中允许跨域;而如果是 nginx 服务器,则在设置中可以如下设置。
location / {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Headers *;
        add_header Access-Control-Expose-HeadersAccept-Ranges,Content-Range;
        add_header Accept-Ranges bytes;
}
对于 pdf.js 端的跨域,必要在 elasticpdf 或 pdf.js 的 viewer.js 中搜索 HOSTED_VIEWER_ORIGINS 并参加域名。
const HOSTED_VIEWER_ORIGINS = ["null", "http://mozilla.github.io", "https://mozilla.github.io"];
4. 导出 pdf 及批注数据

Elasticpdf 所生成批注数据的保存有两种方式,我们保举方式二。pdf.js 默认将批注写入文档,无法分离保存。
4.1 方式一:批注写入PDF

将批注写入到 pdf 中然后下载整个文档,一般用户可以通过Ctrl+S快捷键和 UI 按钮来完成,这种方式完全不必要后端服务的支持。
在必要保存批注后 pdf 至服务器的场景中,可以通过如下代码实现。
// 绑定该函数至 dom 用于触发 pdf 保存
function getPDFData() {
        elasticpdf_viewer.getPDFData();
}

// 接收pdf数据并且上传至服务器
window.addEventListener('message', (e) => {
        if (e.data.source != 'elasticpdf') {
                return;
        }

        // 接收pdf数据
        if (e.data.function_name == 'downloadPDF') {
                let file_name = e.data.content['file_name'];
                let pdf_blob = e.data.content['pdf_blob'];
                let pdf_base64 = e.data.content['pdf_base64'];
               
                // 接收到 pdf 数据,其中 pdf_base64 字符串数据可以快捷上传到服务器
                postService('upload-pdf-data', {
                        'file_name':file_name,
                        'file_id':'123ddasfsdffads',
                        'file_data':pdf_base64,
                });
        }
});
4.1 方式二:批注单独保存

针对云端同步批注的需求,单独将批注文件导出为JSON文件,传输并保存于服务器,之后加载回显后可继续编辑批注。
如许的方式仅需一个在线PDF原文件,只传输很小体积的批注(通常不到 1M 大小),可以节约很多的存储和宽带费用。
// 在 pdf 批注编辑后的回调函数中可以读取所有批注文件并且上传至服务器
window.addEventListener('message', (e) => {
        if (e.data.source != 'elasticpdf') {
                return;
        }

        // pdf 批注编辑回调,可以在此处导出批注并传输到服务器
        if (e.data.function_name == 'annotationsModified') {
                // 仅获取 pdf 批注文件,不写入到 pdf 中
                let this_data = elasticpdf_viewer.pdfAnnotation.outputAnnotations();
                let annotation_content = JSON.stringify(this_data['file_annotation']);
                let file_name = this_data['file_name'];
                postService('upload-annotation-data', {
                        'file_name':file_name,
                        'file_id':'123ddasfsdffads',
                        'file_annotation':annotation_content,
                });
        }
});
5. 重载 pdf 及批注数据

单独将 pdf 批注保存至服务器后,可以在加载 pdf 文件后再次从服务器中下载批注而且重载回显到 pdf 上继续编辑。
// 在 pdf 加载完成后的回调中可以从服务器请求相应的批注并重载于 pdf 上。
window.addEventListener('message', (e) => {
        if (e.data.source != 'elasticpdf') {
                return;
        }

        // pdf 加载完成的回调,可以在此处导入服务器上储存的批注文件
        if (e.data.function_name == 'pdfLoaded') {
                let file_name = 'tutorial.pdf'
                let annotation_content =await postService('get-annotation-data', {
                        'file_name':'tutorial.pdf',
                        'file_id':'123ddasfsdffads',
                });
                // 批注重载回显于当前文件
                elasticpdf_viewer.setPureFileAnnotation({
                        'file_annotation': annotation_content
                });
        }
});
以上的所有与服务器的交互必要前后端协同,后端服务器必要相应步伐来接收和保存数据,对于 Elasticpdf 的用户我们有简单的 PHP、Python 及 Java 代码示例供参考。
前端发起哀求的示例函数 postService() 代码如下。
// 与后端服务器进行网络通信的函数
async function postService(url, data) {
        var new_data = new URLSearchParams();
        var encrpte_data = data;
        new_data.append('data', encrpte_data);
       
        var base_url = "your-server-url";
        var posturl = base_url + url;
        const response = await fetch(posturl, {
                method: 'POST',
                headers: {},
                body: new_data,
        });

       
        const resp = await response.json();
        resp['data'] = JSON.parse(resp['data']);
       
        return resp;
}
总结

至此,pdf.js 及 elasticpdf 集成于 Vue 项目的代码完毕,带有 pdf.js 代码包的 Vue 示例项目包内容已上传至 Github(网址:https://github.com/ElasticPDF/Vue-use-pdf.js-elasticpdf),可以直接下载。Elasticpdf 客户如有其他应用场景需求欢迎接洽我们,我们将为您提供示例代码。
温馨提示:本文首发于 https://www.elasticpdf.com ,转载请注明出处:https://www.elasticpdf.com/blog/vue-pdf-annotation-plugin-library-online-api-examples-zh.html

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Vue 项目利用 pdf.js 及 Elasticpdf 教程