Embedding PDF opened via input file element in HTML

Viewed 1495

I have a simple web app that I am needing someone to select a .pdf from a file server and then display that .pdf on the web page.

I can get the user to select the .pdf via something like <input type="file" id="myFile">

I can also embed a .pdf into an iframe to display on the web app nicely with <iframe src="//path/to/file.pdf" width="100%" height="500px"></iframe>

But how do I display the .pdf the user selected from the input? Is there a way I can pass the value of the input into the src of the iframe? Can I open the .pdf in a new tab or a new html file so I don't have to refresh the entire page?

1 Answers

For anyone needing help with this I found a solution that worked for me.

I created an input for the file I'm wanting to upload. This input calls a JS function that is defined below.

<input type="file" id="file-open" onchange="previewFile()" hidden="hidden" accept=".pdf"><br>

Then created an iframe with size I wanted

<iframe src="" id="iframe-pdf" width="1200px" height="800px"></iframe>

Finally I used JavaScript to convert the file to base64 and use FileReader to open the file within the iframe

function previewFile() {
        const preview = document.querySelector('iframe');
        const file = document.querySelector('input[type=file]').files[0];
        const reader = new FileReader();
        var filename = file.name;

        reader.addEventListener("load", function () {
          // convert file to base64 string
          preview.src = reader.result;
        }, false);

        if (file) {
          reader.readAsDataURL(file);
        }

      }
      </script>
Related