HTML 嵌入式 PDF 所有链接覆盖以在新选项卡中打开 (target= "_blank" )



我目前有一个PDF嵌入到一个网页。PDF中有几个超链接,但是单击时这些链接在父框架中打开。这将把用户带到一个新的页面,没有返回到原始PDF的选项(导航关闭)。我似乎不知道如何让链接在新窗口中打开。

样本PDF

<embed src="https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf" type="application/pdf" />


点击第二个(外部)链接将导航到同一标签页内的另一个网站

工作Plunkr

PDF文档最初是在PowerPoint中创建的,这使我无法添加适当的href属性。是否有一种方法来修改PDF中的链接,以包括target="_blank"?

如果没有,我想知道是否有一些东西我可以包括在html代码,将普遍控制如何打开链接。

欢迎提出任何建议。

谢谢。

只是为了快速限定这个答案,这应该适用于现代浏览器,如果PDF和PDFJS托管在您嵌入的同一域中,则仅适用于

这里的技巧是强制使用PDF.js,并覆盖Chrome的默认行为,将其呈现为扩展。这样,您就可以获得一个带有html元素的iframe,如果您不尝试使用CORS,则可以操作。如果这是针对与CORS相关的用例,那么您就不太走运了,因为编辑CORS pdf有安全风险,因此是不允许的。

你将会想要从按照"强制"使用的例子建立一个站点开始。这里的资源:

https://github.com/mozilla/pdf.js/wiki/Setup-PDF.js-in-a-websitehttps://pdfobject.com/examples/pdfjs-forced.html

你还需要在web服务器上运行它,因为它不能单独在文件系统上正确地服务。欢呼更多的CORS问题。

然后,您将设置您的页面并像这样调用它(基于@Paco的gist)

<html>
<head>
    <title>test pdf</title>
</head>
<div id="pdf"
     style="width:900px; height:500px"></div>
<script src="https://pdfobject.com/js/pdfobject.min.js"></script>
<script>
    var options = {
        pdfOpenParams: {
            page: 1,
            view: "Fit",
            toolbar: 0
        },
        forcePDFJS: true, //*** Forces the use of PDF.js instead of default behavior
        PDFJS_URL: "web/viewer.html" //*** Required to use PDF.js
    };
    PDFObject.embed("../pdf-test.pdf", "#pdf", options);
    document.querySelector('#pdf iframe').onload = function () {
        //can try and hook the PDF.js event for rendering completed and call it then instead. 
        //https://stackoverflow.com/questions/12693207/how-to-know-if-pdf-js-has-finished-rendering
        setTimeout(function () {
            document.querySelector('#pdf iframe').contentDocument.querySelectorAll('a:not(.bookmark)').forEach(function (a, i) {
                a.setAttribute('target', '_blank');
            })
        }, 5000)
    }
</script>
</body>
</html>

使用Adobe Acrobat右键单击链接属性。单击Actions选项卡。如果列出了任何操作,请删除它们,然后选择Run a Javascript。单击"添加"。将出现一个框,供您添加以下javascript。app.launchURL (" http://www.yourlink.com ",真);

最新更新