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

3.4k views Asked by At

i'm having the next problem:

I try to see a pdf in one magento phtml this is my code:

$fileName = Mage::getConfig()->getOptions()->getMediaDir()."/pdf/Gutschein-v2.pdf";

$pdf = new FPDI();
$pdf->addPage();
$pdf->setSourceFile($fileName);

$tplIdx = $pdf->importPage(1);
// use the imported page and place it at point 10,10 with a width of 100 mm

$pdf->useTemplate($tplIdx, 10, 10, 100);

// now write some text above the imported page
$pdf->SetFont('Helvetica');
$pdf->SetTextColor(255, 0, 0);
$pdf->SetXY(30, 30);
$pdf->Write(0, 'This is just a simple text');

//ob_start();
$pdf->Output();
//ob_end_flush(); 

When i comment ob_start(); i see on my screen the next error: FPDF error: Some data has already been output, can't send PDF file

When i don't comment that i see the normal pdf format but not the white page with my pdf, i tried to do that with pure php and everything was ok example: http://milton.bommelme.com/fpdf/pddf.php

but with magento something are not gut, maybe i don't know how to load the pdf or something else. I'm very new with magento.

thank you.

1

There are 1 answers

1
smiggle On

The error "Some data has already been output, can't send PDF file" appears because Magento has already sent the header output. Look at http://php.net/manual/en/function.header.php for further informations.

So the Output() function of FPDF is also sending header informations and it declares the 'Content-Type' to 'application/pdf'. The main problem here is that you cannot just put a PDF file between HTML tags. PDF is an own format and needs a diffrent presantation mechanism than HTML. Like in the example link you gave the PDF file is embeded by the embed-tag with the right Content-Type declaration:

<embed width="100%" height="100%" name="plugin" src="http://milton.bommelme.com/fpdf/pddf.php" type="application/pdf">

There are also other ways to embed a PDF file in HTML: Recommended way to embed PDF in HTML?

EDIT: For example you can create two view actions. The first one renders the HTML. Inside the HTML the embed-tag calls the second action which will generate the PDF. I don't think this is the best solution,but it should work easily:

class Foo_Pdf_Controller_SomeController extends Mage_Core_Controller_Front_Action
{

    public function viewAction()
    {
        // View stuff
    }

    public function getPdfAction()
    {
        // create pdf

        $fpdf->output();
    }
}

The embed-tags calls the getPdf() action:

<embed width="100%" height="100%" name="plugin" src="url_to_getPdf_action" type="application/pdf">