krishna89
krishna89

Reputation: 846

PHP FPDF Failed to load PDF document in Chrome

I am trying to generate a pdf document using fpdf library with php but I am getting an error in chrome as Failed to load PDF document. I am able to view the document properly in firefox. Below is the code I am trying to generate pdf. Can anyone please help? Thanks in advance.

<?php
 ini_set('display_startup_errors', 1);
 ini_set('display_errors', 1);
 error_reporting(-1);
 ob_start();
 $pdf = new FPDF();
 $pdf->AddPage();
 $pdf->SetFont('Arial', 'B', 16);
 $pdf->Cell(40, 10, 'Hello World!');
 header('Content-type: application/pdf');
 header('Content-Transfer-Encoding: binary');
 header("Content-Disposition: inline; filename='example2.pdf'");
 $pdf->Output('example2.pdf', 'I');
 ob_end_flush();
?>

Upvotes: 5

Views: 7508

Answers (2)

websky
websky

Reputation: 3172

I know this old question, but there are requests for answers in the comments. Do not set the header. FPDF generates them.

<?php
   require('fpdf.php');

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

I also recommend http://www.fpdf.org/

Upvotes: 1

Michael
Michael

Reputation: 471

I just spent all morning trying to figure out why I was getting this same error. Worked in Firefox for me, too, but not in Chrome, and it wouldn't open in Adobe either.

The problem was that I was trying to run the script in a function and calling the function from a button. I fixed it simply by adding the script to it's own PHP file, and then linking to the php file directly.

Note: I did try ob_start() and ob_end_flush() and it didn't make a difference in the function. When it's in its own file it doesn't need it anyway.

// file.php
<?php
require $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/eri-webtools-plugin/libraries/fpdf/fpdf.php'; // <-- File path for WordPress plugin
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output(); // To Download, use $pdf->Output('D', 'test.pdf', true);
?>

// html
<a href="file.php">View PDF</a>

Upvotes: 1

Related Questions