Search code examples
javascriptsapui5sap-fiori

How can i open a pdf from a


I was trying to open a pdf from buffer, I try with this code, but when the window open the pdf have the correct number of pages, but all are empty.

Im programin in ui5 and I get this file from ui5 class sap.ui.unified.FileUploader

Thanks in advance and greetings!

openPDF: function (file) {
            if (file && window.FileReader) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    var raw = e.target.result;
                    const url = window.URL.createObjectURL(new Blob([raw], { type: 'application/pdf' }));
                    window.open(url, '_blank', 'fullscreen=yes');

                };
                reader.readAsText(file);
            }
        },

Solution

  • you are reading the file as text with the readAsText() method, the raw data will be a string, not a binary file.

    To fix this, you need to change the readAsText() method to readAsArrayBuffer() method.

    Here is the fixed version of your code:

    openPDF: function (file) {
                if (file && window.FileReader) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var raw = e.target.result;
                        const url = window.URL.createObjectURL(new Blob([raw], { type: 'application/pdf' }));
                        window.open(url, '_blank', 'fullscreen=yes');
                    };
                    reader.readAsArrayBuffer(file);
                }
            },