Search code examples
javascriptangularpdf-viewer

How can we open a pdf file inside an angular application which was already uploaded to the same angular application


I am developing an angular application in which I uploaded a pdf file. I need to open the same pdf file onClick of it inside same application in a modalwindow. I tried using and but no use. I should not use any pdf-viewers


Solution

  • Yes you can just re-use your uploaded pdf like blob and open it in a new Tab:

    var blob = new Blob([pdfBuffer], {type: 'application/pdf'});
    var blobURL = URL.createObjectURL(blob);
    window.open(blobURL);
    

    If you don't want to open it in a new tab, you need to find a Plugin to display blob inside your html. Or maybe with iframe.

    Try using element, requesting resource as a Blob

    html

    <div id="my-container" class="ng-scope pdfobject-container">
        <iframe src="" type="application/pdf" width="100%" height="100%" style="overflow: auto;">
        </iframe>
    </div>
    

    javascript

    var xhr = new XMLHttpRequest();
    // load `document` from `cache`
    xhr.open("GET", "/path/to/file.pdf", true); 
    xhr.responseType = "blob";
    xhr.onload = function (e) {
        if (this.status === 200) {
            // `blob` response
            console.log(this.response);
            var file = window.URL.createObjectURL(this.response);
            document.querySelector("iframe").src = file;
    
        }
    };
    xhr.send();
    

    -> Also see Embed a Blob using PDFObject