AngularJS: Export html table to PDF, Excel or Doc formats.

Ridwan Olalere (Didi Kwang)
2 min readFeb 23, 2015

--

Working on a Logistics Proof-of-Delivery software, we needed to be able to generate and export reports to PDF, Excel and Doc formats.

I built the software using nodejs/express at the backend and AngularJS on the frontend. Meanwhile, there aren’t many directives to enable exporting html table to other formats like PDF, excel, CSV, document, powerpoint.

Thankfully, there is Ngiriraj Html Table Export jQuery plugin which was well written to export html table to other formats.

After looking at the plugin, it wasn’t clear how to use it with AngularJS so i headed to Dan Wahlin’s blog to learn about AngularJS custom directives.

When I finally understood what and how to use AngularJS directives, here is the custom directive I created to help export html table to other formats using html table export jquery plugin

(function(){
//export html table to pdf, excel and doc format directive
var exportTable = function(){var link = function($scope, elm, attr){$scope.$on(‘export-pdf’, function(e, d){
elm.tableExport({type:’pdf’, escape:’false’});
});
$scope.$on(‘export-excel’, function(e, d){
elm.tableExport({type:’excel’, escape:false});
});
$scope.$on(‘export-doc’, function(e, d){
elm.tableExport({type: ‘doc’, escape:false});
});
}return {
restrict: ‘C’,
link: link
}
}
angular
.module(‘CustomDirectives’, [])
.directive(‘exportTable’, exportTable);
})();

The important part in this directive is the link function. The link function of a directive is where the DOM manipulation should happen and it takes 3 params: $scope (scope), element (elm), attribute (attr).

I used the scope object to listen to events which will be triggered from the controller in order to export to any supported format. When an export event is triggered, the element (elm) object in the link function will call ‘tableExport’ method with the least required settings.

Inside the controller I broadcast event when ever an export to pdf /excel/doc is selected like this:

//In controller
$scope.exportAction = function(){
switch($scope.export_action){
case ‘pdf’: $scope.$broadcast(‘export-pdf’, {});
break;
case ‘excel’: $scope.$broadcast(‘export-excel’, {});
break;
case ‘doc’: $scope.$broadcast(‘export-doc’, {});
break;
default: console.log(‘no event caught’);
}
}

In the view you just need to do

<table class=’export-table’></table>

You can reach me at @ridwan_olalere to ask me any question if you have any questions. Thats me below, follow me.

--

--