2017-05-30 12 views
0

我想从我的MySQL数据库的BLOB中获取PDF文件。用于显示PDF的PHP工作正常:如何从数据库/ PHP中以HTML格式嵌入PDF文件

<?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->file;保存$pdf = $row->file;。总是当我尝试调用我的网站的index.php时,它显示出来,PDF文件无法显示,我只能看到浏览器PDF查看器。

有人可以帮助我吗? :/

+0

'$ pdf'应该显示的PDF文件中的第一个脚本的URL。 – Barmar

+0

可能的重复[基础64图像选择和编码从数据库时发现缓慢](https://stackoverflow.com/questions/41228496/slowness-found-when-base-64-image-select-and-encode-from-数据库) – e4c5

+0

谢谢barmar,那工作:)对不起,这个简单的问题 – Flapy

回答

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; 
?> 
相关问题