在HTML中嵌入PDF的推荐方法是什么?

iFrame吗? 对象? 嵌入?

Adobe是怎么说的呢?

在我的例子中,PDF是动态生成的,因此不能在刷新之前将其上传到第三方解决方案。


当前回答

我发现嵌入pdf的最好方法是使用bootstrap,因为它不仅可以显示pdf,而且还可以填充可用空间,您可以根据自己的需要指定比例。下面是我用它做的一个例子:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <div class=" font - family -宋体"> <iframe class="embed- response -item" src="http://example.com/the.pdf" type="application/pdf" allowfullscreen></iframe> . < / div > < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> < script src = " https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js " > < /脚本>

其他回答

这是我对AXIOS和Vue.js所做的:

        axios({
            url: `urltoPDFfile.pdf`,
            method: 'GET',
            headers: headers,
            responseType: 'blob'
        })
        .then((response) => {
            this.urlPdf = URL.createObjectURL(response.data)
        })
        .catch((error) => {
            console.log('ERROR   ', error)
        })

将urlPDF动态添加到HTML:

<object width='100%' height='600px' :data='urlPdf' type='application/pdf'></object>

如果您不想自己托管PDF文件,或者希望使用额外的安全功能(例如防止用户下载PDF文件)自定义PDF查看器。我建议使用CloudPDF。https://cloudpdf.io

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CloudPDF Viewer</title>
  <style>
    body, html {
      height: 100%;
      margin: 0px;
    }
  </style>
</head>
<body style="height: 100%">
  <div id="viewer" style="width: 800px; height: 500px; margin: 80px auto;"></div>
  <script type="text/javascript" src="https://cloudpdf.io/viewer.min.js?version=0.1.0-beta.11"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function(){
      const config = { 
        documentId: 'eee2079d-b0b6-4267-9812-b6b9eadb9c60',
        darkMode: true,
      };
      CloudPDF(config, document.getElementById('viewer')).then((instance) => {

      });
    });
  </script>
 </body>
</html>

在我得到嵌入base64编码PDF的问题之前,因为URI限制,所以任何超过2MB的文件都不会在Chrome上正确呈现。

我的解决方案是:

转换uri编码为Blob: 基于Blob生成临时DOM字符串。 const blob = dataURItoBlob(this.dataUrl); var temp_url = window.URL.createObjectURL(blob); 决定你想把iframe附加到DOM的位置: const target = document.querySelector(targetID); 目标。innerHTML =' <iframe src='${temp_url}' type="application/pdf"></iframe> .

最好的方法可能是使用PDF.JS库。它是一个纯HTML5/JavaScript PDF文档渲染器,没有任何第三方插件。

在线演示: https://mozilla.github.io/pdf.js/web/viewer.html

GitHub: https://github.com/mozilla/pdf.js

如果你不想自己托管PDF.JS,你可以试试DocDroid。它类似于谷歌Drive PDF查看器,但允许自定义品牌。