0

I would like to display a PDF using an img tag, however the img src is not able to read the Data Url below. Any suggestions?

  const handleFile = (e) => {
    let selectedFile = e.target.files[0];
    if(selectedFile){
      if(selectedFile && allowedFiles.includes(selectedFile.type)){
       let reader = new FileReader();
       reader.readAsDataURL(selectedFile);
       reader.onloadend = (e) => {
         setPdfError('');
         const newPdfFiles = [...pdfFiles]
         newPdfFiles.push(e.target.result);
         setPdfFiles(newPdfFiles);
       }
      } else {
        setPdfError('Not a valid pdf')
      }

    } else {
      console.log('please select file')
    }
  <img
        className="d-block w-100"
        src={pdfFiles[0]}
        alt="First slide"
      />
  • 1
    Does this answer your question? [How to display PDF file in HTML?](https://stackoverflow.com/questions/17784037/how-to-display-pdf-file-in-html) – Youssouf Oumar Aug 08 '22 at 18:10
  • The pdfs are not saved in a folder. My webpage will choose them dynamically. – Michael Horvilleur Aug 08 '22 at 18:12
  • 2
    Did you try replacing the `img` with `embed` as shown by the first answer there? – Youssouf Oumar Aug 08 '22 at 18:13
  • I did. That shows the pdf and it works. But I wanted simply the pdf to display without any of the controls. – Michael Horvilleur Aug 08 '22 at 18:17
  • 1
    `readAsDataURL` makes me die inside: `data:` URIs are very inefficient and slow (and block the browser's thread) so you should be using `Blob`/`File` instead. Also, where is `pdfFiles` defined? – Dai Aug 08 '22 at 18:35
  • 1
    _"I would like to display a PDF using an img tag"_ - **you can't**: PDFs are not images. You will need to load it into an ` – Dai Aug 08 '22 at 18:37
  • @MichaelHorvilleur _"But I wanted simply the pdf to display without any of the controls."_ - to my knowledge websites cannot control or configure browsers' PDF viewers - only the end-user can decide if their PDF viewer shows those controls/navigation/pages/thumbnails/ToC/etc or not (and that's _the way it should be_) – Dai Aug 08 '22 at 18:47

0 Answers0