简体   繁体   中英

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.

Change content type to application/pdf and make sure to send the data before the headers:

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM