Saturday, 21 September 2019

JSZip Changes Contents of Files (pdf) While Decompressing

I'm using the FileReader api to load the contents of a file input into the browser's memory. This jsfiddle includes a working example: https://jsfiddle.net/qyh1s60d/

I turn the result into a Uint8Array and display it in a div:

<label for="file-pdf">select a pdf:</label>
<input type="file" id="file-pdf" name="files[]" />
<div id="result-pdf">
</div>

JS

document.getElementById('file-pdf').addEventListener('change', handlePdfSelect, false);
function handlePdfSelect(evt) {
    var files = evt.target.files; // FileList object
    var reader = new FileReader();
    reader.onload = (e)=>{
       var res = new Uint8Array(e.target.result);
       resultPdf.innerHTML = res.slice(0, 5)
    }

    reader.readAsArrayBuffer(files[0]);

  }

So far so good. The div displays an array of numbers as expected.

Next I want to use JSZip to get the same pdf located inside of a zip file. Here's the html:

label for="file-zip">select a zip:</label>
<input type="file" id="file-zip" name="files[]" />
<div id="result-zip">
</div>

And JS

document.getElementById('file-zip').addEventListener('change', handleZipSelect, false); 

function handleZipSelect(evt) {
    var files = evt.target.files; // FileList object
    var reader = new FileReader();
    reader.onload = (e)=>{
       var res = new Uint8Array(e.target.result);
       JSZip.loadAsync(res).then(function(data){
       var pdfs = []       
        Object.keys(data['files']).forEach(f => {
                         if(/\.pdf$/.test(f)){
                             pdfs.push(data['files'][f])
                         }
        })
        var pdfcontents = pdfs[0]['_data']['compressedContent'].slice(0, 5)
        resultZip.innerHTML = pdfcontents;

       })

    }

    reader.readAsArrayBuffer(files[0]);


  }

Even though I use the same pdf in these two file uploads, I get different Uint8Arrays displayed in the browser. Can anyone tell me why these are different, and how I can get the pdf data taken from the zip file to look the same as when it is directly uploaded as pdf?



from JSZip Changes Contents of Files (pdf) While Decompressing

No comments:

Post a Comment