简体   繁体   中英

JavaScript: converting pdf to bytes array and rendering the pdf in UI using HTML5

I need the help on the below two things

1) I need to convert the PDF file data to bytes arrray in JavaScript .

2) Using the above bytes array, I need to render it in the UI as PDF file.

Questions may look like, why I want to convert the PDF file to bytes Stream and again why I want to show it as PDF in UI. But I need to figure out a way for the above two which helps me to solve many issues in my project.

Any suggestions for reading or solutions to above problems will be much appreciable.

Thanks for your time!

please check pdf.js. it may be helpful http://mozilla.github.io/pdf.js

Following code will read the file locally and render the PDF. This will be faster as File doesn't have to get uploaded to server and get downloaded to browser again.

<script type="text/javascript">
//Workaround for a bug on IE.
PDFJS.workerSrc = "pdf.worker.js";

//File from the input element                
inputElement.onchange = function(event) {

    var file = event.target.files[0];
    //Read the file locally using file reader
    var fileReader = new FileReader();  

    fileReader.onload = function() {
        var typedarray = new Uint8Array(this.result);

        // Render PDF
        PDFJS.getDocument(typedarray).then(function(pdf) {

            pdf.getPage(1).then(function getPageHelloWorld(page) {

                var scale = 1.5;
                var viewport = page.getViewport(scale);

                var canvas = document.getElementById('the-canvas');
                var context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;

                page.render({canvasContext: context, viewport: viewport});
            });
        });
    };

    // Read the file into array buffer.
    fileReader.readAsArrayBuffer(file);
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM