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

最佳答案

您应该能够使用FileReader将文件对象的内容作为类型化数组来获取,PDFJS接受该对象(http://mozilla.github.io/pdf.js/api/draft/PDFJS.html)

//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
        PDFJS.getDocument(typedarray).then(function(pdf) {
            // do stuff
        });


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

 }

08-27 00:24