0

我正在使用 PDF.js 库在我的网站中显示 PDf 文件(使用 pdf_viewer.js 在屏幕上显示文档),但我显示的 PDF 文件是机密文件,我需要能够在网站内显示它们但阻止未经授权的公共人员仅通过输入他们的 URL 并看到它们直接显示在他们的浏览器中来查看相同的文件。

我试图在我的 htaccess 文件中添加 Deny from all line,但这当然也阻止了查看器显示文档,所以这似乎是不可行的。显然,任何人都可以简单地查看检查器并查看查看器正在读取的 pdf 文件,因此看起来直接 URL 无论如何都不安全。

我确实读过关于 PDF.js 能够读取二进制数据的信息,但我不知道如何在我自己的文件系统中读取 PDF 并准备它以供图书馆使用,即使这意味着它只是一点点加载速度较慢以获取文件内容并即时准备。

任何人都有一个解决方案,允许 PDFJS 在不透露源 PDF URL 的情况下工作,或者以其他方式使用本地文件调用读取文件?

4

1 回答 1

0

好的,经过一番测试,解决方法很简单:

使用 Ajax 调用函数获取 PDF 数据,该函数可以确定要查看的实际文件。在那个 PHP 文件中... 正常使用 fopen 和 fread 将文件读入内存。使用 base64_encode 转换为 base64 将该字符串传递回调用 Javascript。

在原始调用函数中,使用以下内容将字符串转换为 Uint 数组,然后将其传递给 PDFJS 库...

## The function that turns the base64 string into whatever a Uint8 array is...
function base64ToUint8Array(base64) {
  var raw = atob(base64);
  var uint8Array = new Uint8Array(raw.length);
  for (var i = 0; i < raw.length; i++) {
    uint8Array[i] = raw.charCodeAt(i);
  }
  return uint8Array;
}

## the guts that gets the file data, calls the above function to convert it, and then calls PDF.JS to display it
$.ajax({
type: "GET",
data: {file: <a file id or whatever distinguishes this PDF>},
url: 'getFilePDFdata.php',  (the PHP file that reads the data and returns it encoded)
success: function(base64Data){
      var pdfData = base64ToUint8Array(base64Data);
      ## Loading document.
      PDFJS.getDocument(pdfData).then(function (pdfDocument) {
       ## Document loaded, specifying document for the viewer and
       ## the (optional) linkService.
      pdfViewer.setDocument(pdfDocument);
      pdfLinkService.setDocument(pdfDocument, null);        
    });
   }
});
于 2017-04-23T19:57:08.850 回答