FPDF error: Some data has already been output, can't send PDF

Wondering Coder picture Wondering Coder · Feb 28, 2012 · Viewed 140k times · Source

I am using the fpdf library for my project, and I'm using this to extend one of the drupal module. These lines

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

give me an error: FPDF error: Some data has already been output, can't send PDF

I tried creating this in a separate file outside the drupal area name test.php and when viewed it worked. Anyone here know why this don't work? Or anyone here can point me a right pdf library which I can use in drupal to view HTML to PDF format.

Answer

Gordon Bailey picture Gordon Bailey · Feb 28, 2012

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

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

While this will not (note the leading space before the opening <? tag)

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

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.