如何使用文件输入在 PDFJS 中打开本地 PDF? [英] how to open a local PDF in PDFJS using file input?

查看:49
本文介绍了如何使用文件输入在 PDFJS 中打开本地 PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to know if there is a way to select a pdf file using input type="file" and open it using PDFJS

推荐答案

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

You should be able to use a FileReader to get the contents of a file object as a typed array, which pdfjs accepts (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)以获取更新的答案

The pdfjs API changed at some point since I wrote this first answer in 2015. Updating to reflect the new API as of 2021(thanks to @Chiel) for the updated answer

这篇关于如何使用文件输入在 PDFJS 中打开本地 PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆