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

iFrame吗? 对象? 嵌入?

Adobe是怎么说的呢?

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


当前回答

您可以通过在查询字符串中传递一些选项来控制PDF在浏览器中的显示方式。我很高兴能这样工作,直到我意识到它不能在IE8中工作。:(

它适用于Chrome 9和Firefox 3.6,但在IE8中,它会显示“如果PDF文件无法显示,请在此处插入错误消息”的消息。

不过,我还没有测试上述任何浏览器的旧版本。但这是我的代码,希望能帮到大家。这将缩放设置为85%,删除滚动条,工具栏和导航窗格。如果我发现IE中也能运行的东西,我会更新我的帖子。

<object width="400" height="500" type="application/pdf" data="/my_pdf.pdf?#zoom=85&scrollbar=0&toolbar=0&navpanes=0">
    <p>Insert your error message here, if the PDF cannot be displayed.</p>
</object>

其他回答

我发现嵌入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 " > < /脚本>

我必须用React预览PDF,所以在尝试了几个库之后,我的最佳解决方案是获取数据并emed它。

const pdfBase64 = //fetched from url or generated with jspdf or other library

  <embed
    src={pdfBase64}
    width="500"
    height="375"
    type="application/pdf"
  ></embed>

这是我对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文件,然后使用它的URL:

<iframe src="https://docs.google.com/gview?url=http://example.com/mypdf.pdf&embedded=true" style="width:718px; height:700px;" frameborder="0"></iframe>

重要的是它不需要Flash播放器,而是使用JavaScript。

通过ImageMagick将其转换为PNG,并显示PNG(快速和肮脏)。

<?php
  $dir = '/absolute/path/to/my/directory/';
  $name = 'myPDF.pdf';
  exec("/bin/convert $dir$name $dir$name.png");
  print '<img src="$dir$name.png" />';
?>

如果你需要一个快速的解决方案,想要避免跨浏览器的PDF查看问题,如果PDF只有一页或两页,这是一个很好的选择。当然,您需要在web服务器上安装ImageMagick(这反过来需要Ghostscript),这在共享托管环境中可能不可用。还有一个PHP插件(称为imagick)就像这样工作,但它有自己的特殊要求。