pdf.js和受保护的文件无法以其他方式查看

时间:2017-04-23 06:50:34

标签: file pdf base64 pdfjs

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

我试图在我的htaccess文件的所有行添加Deny,但courfse也阻止了查看器显示文档,所以这似乎是不行的。显然,任何人都可以简单地查看检查器并查看查看器正在阅读的pdf文件,因此看起来直接URL不会以任何方式保密。

我读过关于PDF.js能够读取二进制数据的内容,但我不知道如何在我自己的文件系统中读取PDF并准备供库使用,如果这意味着它是所有加载速度都慢一些,以获取文件内容并准备就绪。

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

1 个答案:

答案 0 :(得分: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);        
    });
   }
});