如何在HTML中嵌入来自Database / PHP的PDF文件

时间:2017-05-30 20:59:22

标签: php html mysql blob embed

我想从我的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;
?>

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

有人可以帮我吗? :/

1 个答案:

答案 0 :(得分:0)

您可以使用iframe元素来显示PDF。 您可以将base 64编码的blob加载到iframe的data属性。 在您的数据属性中,您需要在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;
?>