pdf.js 使用介绍

项目背景

在网页中加载并显示PDF文件是最常见的业务需求。现在的浏览器大多数都自带pdf预览功能,但是每个浏览器的pdf加载器并不一样,工具栏也无法定制化,为了统一不同浏览器pdf预览的一致性,并增加一些自定义功能,我们使用pdf.js来实现pdf的预览。

pdf.js是一款非常优秀的pdf解析工具,其实我们火狐浏览器内核自带pdf预览解析器就是pdf.js这个解析器,我们把pdf在火狐浏览器打开按F12可以看到源码内容。

下面就是项目实现的最终效果,右侧工具栏只留下打印按钮,并在打印的时候触发项目需要的事件,防止复制和下载pdf。

pdf.js的使用

官网地址:http://mozilla.github.io/pdf.js,下载稳定版

项目结构

 项目使用

把项目部署到nginx或者IIS,直接在浏览器中访问viewer.html即可预览我们的pdf,使用方法如下,file为我们要预览的pdf文件地址。

127.0.0.1/pdfjs-2.14.305-dist/web/viewer.html?file=/pdfjs-2.14.305-dist/web/compressed.tracemonkey-pldi-09.pdf

项目自定义

我们需要把右侧工具栏中很多不需要的按钮去掉,并且对按钮事件进行编辑,我们可以使用PDFViewerApplication对象进行调整。

window.onload = function () {
    PDFViewerApplication.appConfig.toolbar.presentationModeButton.classList.add("hidden");
    PDFViewerApplication.appConfig.toolbar.openFile.classList.add("hidden");
    PDFViewerApplication.appConfig.toolbar.download.classList.add("hidden");
    PDFViewerApplication.appConfig.toolbar.viewBookmark.classList.add("hidden");
}
function onbeforeprint() {
    var url = GetQuery1("file");
    var urlParams = parseUrlParams(url);

    $.ajax({
        type: "get",
        url: "/PrintCount?sCardNos=" + urlParams.sCardNos,
        success: function (data) { }
    });
}
window.addEventListener("beforeprint", onbeforeprint);

项目部署

IIS中部署需要增加MIME类型.properties text/plain

其他

预览时禁止自动打印,在viewer.js方法_updateFromSandbox中把以下代码注释掉。

 pdf.js使用demo(已解决隐藏打印下载等按钮)-Javascript文档类资源-CSDN下载

猜你喜欢

转载自blog.csdn.net/qq243348167/article/details/125721254