Search code examples
phpangularjspdfmake

PHP table + pdfMake + AngularJS


I'm a noobie of PHP and AngularJS.

I have a webpage that communicates to a web serves with PHP - AJAX. It queries a database, and echoes the result (a big table) in an html placeholder.

I want to print the content of that table in a downloadable PDF file when the user pushes a button.

I want to use PDFmake and now it works well for test purpose, but how can I pass that content of my table to AngularJS' app? Maybe should I pass table's id to docDefinition content? In that case I don't know how to do that.

Note: Maybe my approach is uncorrent cause I have to relegate PHP to different tasks and use AngularJS to query the Database, but for now I want to mantain this approach.

Thank You


Solution

  • I suggest you use an angular service (as explained in the docs )

    var bigTableApp = angular.module('bigTable',[])
    
    bigTableApp.factory('BigTableSrv', ['$resource',
    function($resource) {
      return $resource('URL_to_php_backend', {}, {
        query: {
          method: 'GET',
          params: {param1: 'value 1', param2: 'value 2'},
          isArray: true
        }
      });
    }
    ]);
    

    Then, you can use it in a controller to fetch data from the back-end and build a table structure in PDFmake's table format:

    bigTableApp.controller('BigTableController', ['$scope', 'BigTableSrv',
      function BigTableController($scope, BigTableSrv) {
        $scope.bigTable = BigTableSrv.query();
        $scope.pdfMakeTable = {
          // array of column widths, expand as needed
          widths: [10, *, 130],
          body: []
        };
    
        $scope.printTable = function() {
          pdfMakeTable.body = $scope.bigTable.map(el => {
            // process each element of your "big table" to one line of the 
            // pdfMake table, size of return array must match that of the widths array
            return [el.prop1, el.prop2, el.prop3]
          });
    
          // create the pdfMake document
          let docDefinition = {
            content: [ pdfMakeTable ]
          }
    
          // print your pdf
          pdfMake.creatPdf(docDefinition).print()
        }
      }
    ]);