Correct HTTP-header for pdf download

I am creating a pdf file with the TYPO3 extension "web2pdf". I am able to download the File on Desktop, but I get two diffenrent errors on Mobile.

  1. IOS is just displaying same code as debugging $pdf (see below)
  2. Android cancels the download and tells me "Server error"

Currently I am just trying to print the PDF(Trigger is a frontend button)

$pdf = $this->getResultPDF();
print($pdf)

$pdf returns me this

string(160607) "%PDF-1.4 %���� 3 0 obj <> /Annots [ 17 0 R 18 0 R ] /Contents 4 0 R>> endobj 4 0 obj <> stream x��X�n�F�������H�����8n �Hb5]]��Ì(*!�����ʢw��y�deh����>�}Q~DjH��uk/&���$���V�yK�gWב\5���3y?�Y=��o9�s�w1�go" U4������=���+)����&��N2y��F$gs)�g9�D������5r�=�G��� �'vt}�x%��ǥ�J,�W�S19퟊��\c��K�)�[��g��wt��ӥ��}E���\<�[�D:;P�1���գ�Ç+IJ�$!3�2���W鵙�a:�9�dj�$n����5X_��Z�_��Q�;/�X:NU��@+��l�k����RD�]�moi��\�Ͻӡ��Ň��18�"�8VqJv�k�ܘ`e��$���X��Ҽ�����NJ�a��X��O"5�,��z�b�"�d���S�}�......

As I said, this i working on Desktop. HTTP-Headers are set to Default (Content-Type:Text/html)

As soon as I change the Content-Header to "application/pdf", the download works fine for all devices. But the PDF-file seems broken now. I can't open the file in any Programm.

I tried to decode the $pdf output as well and put it to a file (To be honest, i don't even know it this could be helpful):

pdf = $this->getResultPDF();

$binary  = base64_decode($pdf);

file_put_contents('filename.pdf', $binary);

header('Content-disposition: attachment;filename="filename.pdf"');
header('Content-Type: application/pdf');
header('Content-Description: File Transfer');
header('Pragma: public');

print($binary);

Am I using wrong php functions for pdf download? Is there any specific Header I need for PDF-Download on mobile devices?


Solution 1:

Should be enough:

// force download in the browser
header('Content-Disposition: attachment; filename="filename.pdf"');

// tell the browser it's a pdf document
header('Content-Type: application/pdf');

// don't allow to cache
header('Cache-Control: private');

// if you have pdf contents in a variable report its size
// otherwise the browser won't show download progress
// you should skip this line for large files
header('Content-Length: ' . strlen($pdf));

// flush the output directly
// don't do this for large files
readfile($pathToThePdf);

// OR
// output in chunks for large files
$handle = fopen($pathToThePdf);
while (!feof($handle)) {
    $buffer = fread($handle, 8192);
    if (false !== $buffer) {
        echo $buffer;
    }
}
fclose($handle);

If you encounter any 500 errors then you should check for errors in the error log why's that happening.