skip to Main Content

I am fetching some PDFs from an API and showing them in an iframe by setting the URLs to the iframe‘s src. Imagine it’s something like example.com/pdf1.pdf, exmaple.com/pdf2.pdf, etc.

Some of the URLS correctly respond with Content-Type: application/pdf.

However, a few of the responses have this instead: Content-Type: application/octet-stream.

This causes the PDF to be downloaded automatically by the browser, rather than be shown in the iframe.

I do not control the API.

I would strongly prefer jnot to build a proxy server.

Is there any client-side / Javascript solution to making the PDF render in the iframe even with application/octet-stream as the content type?

Some extensions can override the headers, but this site needs to work for other users and I can’t expect them to all install the extensions.

2

Answers


  1. Since you don’t have a JS solution to change the content type of the offending PDFs, I will offer you a reasonably acceptable alternative solution.

    Google Docs, offer a online PDF viewer which can be hot-linked with the desired pdf-url which you can then embed into an iframe!

    Like this…

    var Url='https://www.orimi.com/pdf-test.pdf'; // the pdf you want to load (NB: this one has the right MIME type though)    
    
    var Gdocs='https://docs.google.com/gview?url='+Url+'&embedded=true'; // Google Docs url and way of passing the pdf to view
    

    Now all you need is a fast way to get the content type of a pdf in order to decide which url to feed into your iframe…

    fetch(Url).then(response=>{ 
    
     let CT=response.headers.get('Content-Type');
    
     if(CT=='application/pdf'){I.src=Url;} else {I.src=Gdocs;} 
    
    }).catch(error=>{alert(error);});
    

    Either way the PDF will end up displaying in your iframe!

    Test HTML used…

    <iframe id="I" src="" width="640" height="480" frameborder="1"></iframe>
    
    Login or Signup to reply.
  2. Their are a couple of JS librairies that render PDFs in the browser.

    These can also be combined with the iframe-resizer library to have the iframe match the size of the document if that is useful to you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search