Search code examples
phppdfexportmpdf

PHP: MPDF export from multiple textares/textboxes


So, I'm using MPDF to export data/content from one textarea. It works perfectly fine for one textarea, but what happens when I need to export multiple texboxes with a button click? Doing it this way (as shown below) it only exports the last textarea only. I need your help to figure this out how to export from multiple textareas. Thank you.

My form. The textareas with its content is being echoed/displayed using a while loop as shown below.

<form method='post' action='thanks.php' enctype="multipart/form-data">

  <?php
  while ($rows = mysqli_fetch_assoc($result)) {
  ?>

  <textarea name="editor" id="editor">
  <?= $rows['Content']; ?>
  </textarea><br>

  <input type="submit" name="export" value="Export" id="export" class="btn third">

  <?php
  }
  ?>

</form>

Export coding.

<?php

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

if ((isset($_POST['editor'])) && (!empty($_POST['editor']))) {

    $pdfcontent = $_POST['editor'];

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

    // $mpdf->SetDisplayMode('fullpage');
    // $mpdf->list_indent_first_level = 0;

    //output in browser
    $mpdf->Output('mypdf.pdf', 'D');

}

?>


Solution

  • You have to give each textarea another name, so each one gets included when you submit the form. One way of doing this is to use a counter:

    <form method='post' action='thanks.php' enctype="multipart/form-data">
    <?php
    
    $areaCount = 1;
    
    while ($rows = mysqli_fetch_assoc($result)) {
    
        echo '<textarea name="editor_' . $areaCount . '" id="editor">'.
             $rows['Content'] . '</textarea><br>';
    
        $areaCount++;
    
    }
    
    ?>
    
    <input type="submit" name="export" value="Export" id="export" class="btn third">
    </form>
    

    Now when the form is submitted you have to find all the areas again:

    <?php
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    if (isset($_POST['export'])) {
    
        $pdfcontent = '';
        $areaCount  = 1;
    
        while (isset($_POST['editor_' . $areaCount])) { 
    
            $pdfcontent .= $_POST['editor_' . $areaCount];
            $areaCount++;
    
        }
    
        $mpdf = new \Mpdf\Mpdf();
        
        $mpdf->WriteHTML($pdfcontent);
    
        // $mpdf->SetDisplayMode('fullpage');
        // $mpdf->list_indent_first_level = 0;
    
        //output in browser
        $mpdf->Output('mypdf.pdf', 'D');
    
    }
    
    ?>