Search code examples
javascriptpdfwindow

How to open PDF file from javascript, but not in new window?


I need open PDF file from my JS code, but <a href="#" onclick="window.open('http://linktoPDF', 'NewWin');">link</a> in not good aproach.

I want to open this PDF in something like pdf viewer in current page.


Solution

  • Don't link directly to the PDF. Create a new HTML page that has a single "object" tag that takes up the entire window; basically an HTML wrapper. Set the data property of the object to the PDF you originally wanted to link to. Set the link in your source HTML to point to the HTML wrapper. That way you can control how the wrapper loads and the PDF just shows up in the page. The HTML would look something like this...

    <body style="overflow:hidden;height:100vh;margin: 0;padding: 0;border: 0;">
        <object data="YOUR_PDF.pdf" type="application/pdf" style="width: 100%; height: 100vh"></object>
    </body>
    

    The link in your document would be a normal link to the above HTML page. It just looks like it links directly to a PDF.