Ben Ben - 1 month ago 25
PHP Question

PHP embedd a PDF in a browser window

This code opens a PDF in a blank browser window with no extra style.

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="'.basename($complete_path).'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
header('Content-Length: ' .filesize($complete_path));

$success = readfile($complete_path);


But I want to apply more info and some styling too. So I tried this code :

echo '<!DOCTYPE html>';
echo '<head>';
echo '<meta charset="UTF-8">';
echo '<title>'.$file_name.'</title>';
echo '<link rel="stylesheet" type="text/css" href="css/docs.css" />';
echo '</head>';

echo '<body >';

echo'<div class="frame">';
$success = readfile($complete_path);
echo'</div>';

echo '</body>';


Obviously this fails, it was a quick try. So how to embedd a PDF file in a styled browser page ? I do not want to download it on disk.

Answer

To embed you can use <embed> to display PDF without downloading it :

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

Now the PHP way :

<?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;
?>