简体   繁体   中英

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.

Unfortunately, the behaviour is all down to the PDF reader software that the user has installed, so you can't control it with a simple link.

That is, the PDF reader software installed on the user's PC overrides the browser's 'download' behaviour, and does what it likes with the PDF - whether that is launching it in a separate window, or a client application.

To render it in the same window you need to instruct a PDF viewer that you control.

There are a few if you google, and the one I prefer is the open source pdf.js

Alternatively, you may be able to find an online 3rd-party viewer that you can call via a URL, passing it the link to your PDF as part of the URL.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM