How can one optimize the code in the WriteHTML function to avoid errors like "Some data has already been output, can't send PDF file"?

The issue of "Some data has already been output, can't send PDF file" occurs when there is output sent to the browser before attempting to send a PDF file. To solve this, you can use output buffering to capture any output before sending the PDF file, ensuring that no data is sent to the browser prematurely.

function WriteHTML($html){
    ob_start(); // Start output buffering
    require_once('tcpdf.php'); // Include TCPDF library
    $pdf = new TCPDF(); // Create new TCPDF object
    $pdf->SetPrintHeader(false);
    $pdf->SetPrintFooter(false);
    $pdf->AddPage();
    $pdf->writeHTML($html, true, false, true, false, '');
    ob_end_clean(); // Clean (erase) the output buffer and turn off output buffering
    $pdf->Output('output.pdf', 'D'); // Send the PDF file to the browser for download
}