'mPDF error: Some data has already been output to browser, can't send PDF file

I am getting such error whn I try to use mPDF. mPDF error: Some data has already been output to browser, can't send PDF file

Here is the code:

<?php
include("mpdf60/mpdf.php");

$mpdf=new mPDF('c','A4','','' , 0 , 0 , 0 , 0 , 0 , 0); 

$mpdf->SetDisplayMode('fullpage');

$mpdf->list_indent_first_level = 0;  // 1 or 0 - whether to indent the first level of a list

$mpdf->WriteHTML(file_get_contents('invoice.html'));

$mpdf->Output();


$to      = $_POST["email"];
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
    'Reply-To: [email protected]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

Have you ever had this problem? How to solve it? Thanks



Solution 1:[1]

Try using ob_end_clean before include("mpdf60/mpdf.php"); May be that solves your problem.

Solution 2:[2]

I'm having the same problem and from the answer of Khushal Nayani, I figured what's wrong: in my *.php file I'm printing the $PDFcontent (( print($PDFcontent); )) as a checking step along with calling the new pdf: (( mpdf = new \Mpdf\Mpdf... etc. )). And hence the error: Data has already been sent to output...

And yes, when I commented the (( //print($PDFcontent) )) out things worked.

Solution 3:[3]

I have got the same error.

Data has already been sent to output, unable to output PDF file

This means before creating pdf with mPDF some data is stored in the buffer which gets send to the browser. Therefore it is unable to create the PDF.

Add this php built-in function below the first line of your page where you are preparing the data for the pdf.

ob_start();

And add this built-in php function before mPDF code (before where you are calling mpdf).

ob_end_flush();

require_once __DIR__ . '/vendor/autoload.php';

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output();

This will clear all buffer output before processing mPDF.

Make sure if you use any functions then keep it in the same page don't include functions page where you have kept your all functions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raheel Shahzad
Solution 2 Dharman
Solution 3 Tom