【问题标题】:How to embedd a PDF file from Database / PHP in HTML如何在 HTML 中嵌入来自数据库/PHP 的 PDF 文件
【发布时间】:2017-10-31 11:51:20
【问题描述】:

我想从我的 MySQL 数据库中的 BLOB 中获取 PDF 文件。用于显示 PDF 的 PHP 工作正常:

<?php


$mysqli = new mysqli("192.168.1.11", "root", "password", "DB");
if ($mysqli->connect_errno) {
    die("Connection refused: " . $mysqli->connect_error);
}

try{
   $sql = "SELECT file FROM table WHERE id = 1";
   $result = mysqli_query($mysqli, $sql);        
   $row = mysqli_fetch_object($result);
   header('Content-type: application/pdf');

   echo $row->file;   

}catch(Exception $e){
    echo "caught exception: ", $e->getMessage(), "\n";
}

?>

现在我想将此 PDF 文件嵌入到 HTML 中。我试过这样的事情:

<?php
$pdf = "MY_PDF_FILE.PDF";        ◄
echo <<<BLOCK
  <!DOCTYPE html>
  <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <title>Embeded PDF</title>
    </head>
    <body>
      <embed src="$pdf" type="application/pdf" height="25%" width="25%">
     </body>        ▲
  </html>
    BLOCK;
?>

我尝试用$pdf = $row-&gt;file;$row-&gt;file; 保存在$pdf 中。总是当我尝试调用我网站的 index.php 时,它会显示 PDF 文件无法显示,我只能看到浏览器的 PDF 查看器。

有人可以帮我解决这个问题吗? :/

【问题讨论】:

标签: php html mysql blob embed


【解决方案1】:

您可以使用 iframe 元素来显示 PDF。 您可以将 base 64 编码的 blob 加载到 iframe 的数据属性中。 在您的数据属性中,您需要在 base64 字符串之前写入:'application/pdf;base64,'。

<iframe data="data:application/pdf;base64,B64STRINGHERE" type="application/pdf" style="height:200px;width:60%"></iframe>

所以你必须这样做:

<?php
    // Connection to DB + Retrive blob
    // We assume that your '$row->file' contains Blob data.
    // So encode '$row->file' to base 64
    $pdf = base64_encode($row->file); // BLOB TO BASE64
    echo <<<BLOCK
    <!DOCTYPE html>
    <html>
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
          <title>Embeded PDF</title>
        </head>
        <body>
          <iframe data="data:application/pdf;base64,$pdf" type="application/pdf" style="height:200px;width:60%"></iframe>
        </body>        
    </html>
    BLOCK;
?>

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 2014-04-16
    • 2013-09-10
    • 2013-02-15
    • 2012-06-17
    • 2020-11-17
    • 2011-11-28
    • 2019-07-14
    • 1970-01-01
    相关资源
    最近更新 更多