0

This is my HTML code:

<div class="mb-3" style="width: 50%; margin: 0 auto; border: 2px solid white;">
     <label for="file">Select your snippet file :</label><br>
     <input type="file" id="myfile" name="myfile" accept=".pdf,.jpg,.png">
</div>
<div class="container">
     <span id="preview_text" style="text-align: center; vertical-align: middle; line-height: 200px; color: red;">No preview available</span>
     <img id="scanOutput" src="#" style="height: 200px;"/>
</div>

This is my javascript:

myfile.onchange = evt => {
    const [file] = myfile.files
    if (file) {
        if(file.type=="image/jpeg" || file.type=="image/png"){
            if(document.getElementById("preview_text")!=null)
                document.getElementById("preview_text").remove();
            if((file.size/1024)<200){
                scanOutput.src = URL.createObjectURL(file);
                document.getElementsByClassName("container")[0].style.border="2px solid green";
            }
            else{
                scanOutput.src="#";
                if(document.getElementById("preview_text")==null){
                    var elem=document.createElement("SPAN");
                    elem.id="preview_text";
                    elem.innerText="File size should not be greater than 200kb";
                    elem.style="text-align: center; vertical-align: middle; line-height: 200px; color: red;";
                    document.getElementsByClassName("container")[0].appendChild(elem);
                }
                document.getElementsByClassName("container")[0].style.border="2px solid red";
            }
        }
        else if(file.type=="application/pdf"){
            //how do I preview the pdf into my <img> field?
        }
    }
}

I can preview the jpg/png images in my <img> tag, but not the pdf. I want to also be able to preview the pdf files in my img field. How do I do that?

  • You can't preview a PDF in an tag, but you can in an – Lionel Ding Mar 10 '22 at 07:57
  • so is there a way I can replace my `` tag with an ` –  Mar 10 '22 at 08:05
  • @Abhishek you have to first generate a pdf file then and need to temporarily upload the PDF to somewhere then use that link as an iframe source – udoyhasan Mar 10 '22 at 08:19

1 Answers1

0

You can't use a HTML <img> tag to preview a .pdf file as souce. The proper way is to embed the .pdf via <iframe> or <embed> tag.

For more information on this please refer to: Recommended way to embed PDF in HTML?

udoyhasan
  • 1,527
  • 5
  • 19