Как динамически генерировать PDF-файлы из TCPDF на новой странице для каждой группы - PullRequest
0 голосов
/ 13 мая 2019

Пробую библиотеку TCPDF.Я хочу использовать TCPDF для динамического создания PDF-документов из базы данных MySQL с использованием PHP.Требуемое решение должно выглядеть следующим образом:

Pdf-решение

На каждой странице должны быть напечатаны данные клиента, после того, как это будет сделано, перейдите на другую страницу дляследующий клиент, пока все они не будут распечатаны.

В приведенном ниже примере кода достигается печать сведений о клиенте на каждой странице, но я не могу понять, как напечатать итоги на каждой странице.

    <?php
    ob_start(); 
    set_time_limit(300000);
    ini_set('memory_limit','2048M');
    require_once('../config/lang/eng.php');
    require_once('../tcpdf.php');
    require_once("../../connect.php");


    // extend TCPF with custom functions
    class MYPDF extends TCPDF {

        // Load table data from database
        public function LoadData($sql) {
            // Read database records
            $pdoGetData = new PDOConfig();
            $resultset = $pdoGetData->query($sql);
            $data = array();
            foreach( $resultset as $row)
            {
                $data[] = array(
                                  //Controlling the page breaks
            'Client' => $row['Client'],
            'AmountDue' => $row['AmountDue'],                 
            'Item'=>$row['Item'],
            'Installments '=>$row['Installments '], 
                                );  
            }
        //Close Connection
        $pdoGetData=null;

            return $data;
        }

        // Load table summary data from database
        public function LoadSummaryData($sql) {
            // Read database records
            $pdoGetData = new PDOConfig();
            $resultset = $pdoGetData->query($sql);
            $data = array();
            foreach( $resultset as $row)
            {
                $data[] = array(
                                  'TotalAmountDue' => $row['TotalAmountDue'],

                                );  
            }
        //Close Connection
        $pdoGetData=null;

            return $data;
        }

        // Colored table
        public function ColoredTable($header,$data,$dataSummary) {

            $this->SetLineWidth(0.3);
            // row widths
            $w = array(32, 43, 45, 40, 40, 30, 35,30);

            // print header
            $this->PrintHeader($header,$w,$data[0]['Client'],$data[0]['TotalAmountDue']);

            // Data
            $fill = 0;
            $dimensions = $this->getPageDimensions();
            $hasBorder = false; //flag for fringe case
            $currentCourseType = $data[0]['Client']; //check for group headers

    foreach($data as $row) 
    //foreach(array_merge($data, $dataSummary) as $row)
    {
        $rowcount = 0;
        $rowHeight = 0;

        //check if group data has changed
        if ($currentCourseType <> $row['Client'])
        {
            $currentCourseType = $row['Client'];
            //force a page break and rewrite grid headings here
            $this->AddPage();
            // print header
            $this->PrintHeader($header,$w,$row['Client'],$row['TotalAmountDue']);
            $borders = 'LTRB';
        }

        //work out the number of lines required  
        $rowcount = max($this->getNumLines($row['Client'], $w[0]));
        $rowHeight = $rowcount   > 8 ? $rowcount : 8;
        //$rowHeight = $rowcount + 3  > 12 ? $rowcount : 12;
        $startY = $this->GetY();

        if (($startY + $rowHeight) + $dimensions['bm'] > ($dimensions['hk'])) {
            //this row will cause a page break, draw the bottom border on previous row and give this a top border
            //we could force a page break and rewrite grid headings here
            $this->AddPage();
            // print header
            $this->PrintHeader($header,$w,$row['Client'],$row['TotalAmountDue']);

            /*if ($hasborder) {
                $hasborder = false;
            } else {
                $this->Cell(array_sum($w),0,'','T'); //draw bottom border on previous row
                $this->Ln();
            }*/
            $borders = 'LTRB';
        } elseif ((ceil($startY) + $rowHeight) + $dimensions['bm'] == floor($dimensions['hk'])) {
            //fringe case where this cell will just reach the page break
            //draw the cell with a bottom border as we cannot draw it otherwise
            $borders = 'LRB';   
            $hasborder = true; //stops the attempt to draw the bottom border on the next row
        } else {
            //normal cell
            $borders = 'LRB';
        }

        //now draw it
        $this->MultiCell($w[0],$rowHeight,$row['Item'],$borders,'L',$fill,0);
        $this->MultiCell($w[1],$rowHeight,$row['Installments'],$borders,'L',$fill,0);
        $this->MultiCell($w[2],$rowHeight,$row['AmountDue'],$borders,'L',$fill,0);

        $this->Ln();
        //$fill=!$fill;

    }
      //last page (summary page)
        //$this->AddPage();
        $this->setCellPaddings(3,2,3,2);
        $borders = 'LTRB';
        $this->SetFont('', 'B',8);
        //$this->MultiCell(array_sum($w), 15, 'Report Summary', 0, 'L', 0, 0,'', '', true);
        //$this->Ln();

        //$this->MultiCell(array_sum($w)/2, 8, 'District Name', 1, 'L', 0, 0,'', '', true);
        //$this->MultiCell(array_sum($w)/2, 8, 'Total', 1, 'R', 0, 0,'', '', true);
        //$this->Ln();
        $borders = 'LRB';
        $reportTotal = 0;
      foreach ($dataSummary as $rowSummary)
      {
        //$this->MultiCell(array_sum($w)/2,$rowHeight,$rowSummary['Client'],$borders,'L',$fill,0);  
        //$this->MultiCell(array_sum($w)/2,$rowHeight,$rowSummary['Total'],$borders,'R',$fill,0);   
        //$this->Ln();
        $reportTotal += $rowSummary['Total'];
      }
        // print the report totals
        //$this->MultiCell(array_sum($w)/2,$rowHeight,'Total',$borders,'L',$fill,0);    
        //$this->MultiCell(array_sum($w)/2,$rowHeight,$reportTotal,$borders,'R',$fill,0);   
    }

        private function PrintHeader($header,$w,$Client,$TotalAmountDue)
        {   

            $this->SetTextColor(0);
            $this->setCellPaddings(3,2,0,0);

            //report title
            $this->SetFont('', 'B',20);
            $this->Cell(array_sum($wb),0,'','B',0,'C');
            $this->Ln();

             $wb = array(32, 43, 45, 40, 40, 30, 30,5);
            //print the group headers
            $this->SetFont('', 'B',10);
            $this->Cell((array_sum($wb)/2),0,'To: '.$Client,'',0,'L');
            $this->Ln();


            // print table Header 
            $this->SetFont('', 'B',8);
            $num_headers = count($header);
            for($i = 0; $i < $num_headers; ++$i) {
                $this->MultiCell($w[$i], 8, $header[$i], 1, 'L', 0, 0,'', '', true);
            }
            $this->Ln();

            // Color and font restoration
            //$this->SetFillColor(224, 235, 255);
            $this->SetTextColor(0);
            $this->SetFont('','',7);
        }
    }

    // create new PDF document
    $pdf = new MYPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Testing');
    $pdf->SetTitle('Testing');
    $pdf->SetSubject('Testing');
    $pdf->SetKeywords('Testing');

    // set default header data
    //$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
    // remove default header/footer
    $pdf->setPrintHeader(false);

    // set header and footer fonts
    //$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    //set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);
    //$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(15);

    //set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    //set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    //set some language-dependent strings
    $pdf->setLanguageArray($l);

    // ---------------------------------------------------------

    // set font
    $pdf->SetFont('helvetica', '', 8);

    // add a page
    $pdf->AddPage();

    //Column titles
    $header = array('Item', 'Installments', 'DueAmount');

        //variables to load data
        if (isset($_POST['ClientID']) && (trim($_POST['ClientID']) !='%')) {
            $filter=$filter."  AND  (a.ClientID LIKE '".$_POST['ClientID']."') ";
        }

        //SQL to get the client details, grouped by client ID
        $sql='CALL sp_AllClients("'.$filter.'")';
        //SQL to get the client totals for amount due, grouped by client ID
        $sqlSummary='CALL sp_AllClientsSummary("'.$filter.'")';

    //Data loading
    $data = $pdf->LoadData($sql);
    $dataSummary = $pdf->LoadSummaryData($sqlSummary);

    // print colored table
    $pdf->ColoredTable($header, $data, $dataSummary);

    // ---------------------------------------------------------

    ob_end_clean();
    $pdf->Output('clientsReport.pdf', 'I');
    //============================================================+
    // END OF FILE                                                
    //============================================================+
...