如何使用文件输入在 PDFJS 中打开本地 PDF?

新手上路,请多包涵

我想知道是否有办法使用 input type="file" 选择 pdf 文件并使用 PDFJS 打开它

原文由 user2422940 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 699
1 个回答

您应该能够使用 FileReader 将文件对象的内容作为类型数组获取,pdfjs 接受( https://mozilla.github.io/pdf.js/examples/

 //Step 1: Get the file from the input element
inputElement.onchange = function(event) {

    var file = event.target.files[0];

    //Step 2: Read the file using file reader
    var fileReader = new FileReader();

    fileReader.onload = function() {

        //Step 4:turn array buffer into typed array
        var typedarray = new Uint8Array(this.result);

        //Step 5:pdfjs should be able to read this
        const loadingTask = pdfjsLib.getDocument(typedarray);
        loadingTask.promise.then(pdf => {
            // The document is loaded here...
        });


    };
    //Step 3:Read the file as ArrayBuffer
    fileReader.readAsArrayBuffer(file);

 }

编辑:自从我在 2015 年写下第一个答案以来,pdfjs API 在某个时候发生了变化。更新以反映 2021 年的新 API(感谢@Chiel)以获取更新的答案

原文由 Sam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题