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

标签 javascript html pdf powerpoint

我目前在网页中嵌入了 PDF。 PDF 中有几个超链接,但单击时链接会在父框架中打开。这会将用户带到一个新页面,并且没有返回原始 PDF 的选项(导航已关闭)。我似乎无法弄清楚如何让链接在新窗口中打开。

示例 PDF

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

问题

Clicking second(External) link on this PDF will navigate to another website within the same tab.

工作 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-website https://pdfobject.com/examples/pdfjs-forced.html

您还需要在网络服务器上运行它,因为它不能单独从文件系统正确地服务器。万岁更多 CORS 问题。

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

<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>

关于javascript - HTML 嵌入式 PDF 所有链接覆盖以在新选项卡中打开(目标 ="_blank"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32228564/

相关文章:

javascript - 莫里斯图 - 如何格式化悬停标签

javascript - 如何格式化列中显示的数据

jquery - overflow :hidden div 检查一个LI是否溢出

java - PDFTextStripper 解析编码错误

python - 在Python中从PDF中提取具有特定标题的数据

javascript - jsPlumb repaintEverything 不适用于除 Firefox 之外的所有浏览器

javascript - onclick 需要在插入一些文本后单击几次

html - 如何在左侧 float 更多按钮

html - 滚动=不!不隐藏滚动条

c# - 将html文件转换成PDF文件?