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

问题描述 投票:8回答:1

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

javascript html pdf
1个回答
22
投票

您应该能够使用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);

 }
© www.soinside.com 2019 - 2024. All rights reserved.