Search code examples
phppdffpdf

PHP pdf creation downloads pdf as corrupt


I have a piece of code that creates a correct pdf on the server, but when I try to download it it, it downloads as corrupt:

for($i = 0 ; $i < $num_tokens ; $i++){

    #$tokens[$i] = pronto_aes_decrypt( $token_crypt[$i] , $prontoKey );
    $tokens[$i] = pronto_aes_decrypt( $token_crypt[$i] , $prontoKey );

    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,$tokens[$i]);


}
unlink("tokens.pdf");
$pdf->Output('tokens.pdf','F');  

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="tokens.pdf"');

EDIT: Here is how the code looks now with correct content-type and correct Output function placement:

$pdf = new FPDF( ); 

for($i = 0 ; $i < $num_tokens ; $i++){

    $tokens[$i] = pronto_aes_decrypt( $token_crypt[$i] , $prontoKey );

    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,$tokens[$i]);

}
unlink("tokens.pdf");

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="tokens.pdf"');
$pdf->Output('tokens.pdf','F');

The error still persists though.


Solution

  • you need to flush your buffer.

      $pdf = new FPDF();
            $pdf->AddPage();
            $pdf->SetFont('Arial', 'B', 16);
            $pdf->Cell(40, 10, 'Hello World!');
            $pdf->Output('I');
            ob_flush();