Uncaught Mpdf\MpdfException: Data has already been sent to output

32 views Asked by At

I am trying to use mPDF library on my wordpress (wp-admin) but i am getting this error:

Fatal error: Uncaught Mpdf\MpdfException: Data has already been sent to output (\wp-includes\script-loader.php at line 2925), unable to output PDF file

so this is the WordPress function i have written

function display_student_details() {
    // Check if student ID is provided in the query string
    if (isset($_GET['id'])) {
        $student_id = intval($_GET['id']); // Get student ID from the query string

        // Start output buffering
        ob_start();
       

        global $wpdb;

        // Fetch student details from the database
        $student_details = $wpdb->get_row(
            $wpdb->prepare("SELECT id, firstName, secondName FROM wrbc_studentReg WHERE id = %d", $student_id),
            ARRAY_A
        );

        if ($student_details) {
           
            // Prevent WordPress from sending additional content
            if (ob_get_length()) {
                ob_end_clean();
            }

            // Set up Mpdf
            require_once __DIR__ . '/mpdf/vendor/autoload.php';

            // Create new PDF document
            $mpdf = new \Mpdf\Mpdf();

            // Add content to PDF
            $mpdf->WriteHTML('<h1>Student Details</h1>');
            foreach ($student_details as $key => $value) {
                $mpdf->WriteHTML("<p><strong>{$key}:</strong> {$value}</p>");
            }

            // Output PDF
            $mpdf->Output('student_details.pdf', 'I');
            exit; // Stop execution after generating PDF
            ob_end_clean();
        } else {
            echo '<p>No details found for the selected student.</p>';
        }
    } else {
        echo '<p>No student ID provided.</p>';
    }
}

I tried to follow the solution from this stackoverflow question by using ob_end_clean but in vain.

0

There are 0 answers