Skip to content

JS 通过 input 加载 PDF

Published: at 05:42 PMSuggest Changes

记一下 JS 通过 input 加载 pdf

//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);
};

另外一个方法,好像都差不多,不过上面的方法传值不是 { data: myData }

var reader = new FileReader();
    reader.readAsArrayBuffer(input.files[0]);
    reader.onload = function (e) {

     var myData = new Uint8Array(e.target.result)
	 var docInitParams = { data: myData };

	 PDFJS.getDocument(docInitParams).then(function(pdf) {.....})

}

参考文章


Previous Post
JavaScript 将 input File 对象转换为 Blob 对象
Next Post
Sequelize 不区分大小写查找数据