Search code examples
phppdfpreview

Preview a PDF file in browser with PHP


I've a question for you. I would like to display a PDF onto my web browser.

Furthermore, I made this code. It works with Firefox but unfortunately not with Chrome.

$content = file_get_contents($path);
var_dump($content);
header("Content-Disposition: inline; filename=$path");
header('Content-Transfer-Encoding: binary');
header("Content-type: application/pdf");
header("Cache-Control: private, must-revalidate, post-check=0, pre-check=0, public");
header("Pragma: public");
header("Accept-Ranges: bytes");
echo $content;

Can you help me?

Thank you in advance!


Solution

  • You must not have a var_dump() before the headers (unless you use output buffering without telling us). There must not be any output before sending headers. Also, if you use var_dump() to dump the PDF's contents that will introduce surrounding artifacts which probably cause problems with most PDF viewers.

    For troubleshooting, please try this minimal working example:

    <?php
    $path = './path/to/file.pdf';
    
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename='.$path);
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    
    readfile($path);
    

    Just as an aside, it is generally also a good idea not to use a closing PHP tag (?>) in order to avoid any unwanted accidental whitespace at the end of the file, which could be causing problems; and to stick with one type of quite marks ' or " for your strings.