Over a million developers have joined DZone.

Building a Simple AngularJS Print Directive

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Last week I wrote a simple print button directive for an application that uses AngularJS as its client-side framework. The requirement of the button was to enable the printing of a DOM element that included some content. In this post I’m going to describe how I build this directive but I won’t cover what are AngularJS directives. There are many good online resources about AngularJS directives, so please read one of them before reading this post. The solution I use for the directive is based on this jsFiddle: http://jsfiddle.net/95ezN/121/.

The Directive Code

We will first start with the directive itself:

(function (angular) {
    'use strict';

    function printDirective() {
        var printSection = document.getElementById('printSection');

        // if there is no printing section, create one
        if (!printSection) {
            printSection = document.createElement('div');
            printSection.id = 'printSection';
            document.body.appendChild(printSection);
        }

        function link(scope, element, attrs) {
            element.on('click', function () {
                var elemToPrint = document.getElementById(attrs.printElementId);
                if (elemToPrint) {
                    printElement(elemToPrint);
                    window.print();
                }
            });

            window.onafterprint = function () {
                // clean the print section before adding new content
                printSection.innerHTML = '';
            }
        }

        function printElement(elem) {
            // clones the element you want to print
            var domClone = elem.cloneNode(true);
            printSection.appendChild(domClone);
        }

        return {
            link: link,
            restrict: 'A'
        };
    }

    angular.module('app').directive('ngPrint', [printDirective]);
}(window.angular));

The code here is very simple and lets try to understand what it does:
When the directive is created, we first check if a print section DIV (which has the printSection id) is part of the DOM.  If the DIV doesn’t exists, we create it and append it to the body of the web page. That print section will be used for attaching DOM elements that we want to print.
 
Later on, we create the directive link function which receives both the element and its attributes as arguments. We expect that there will be a printElementId attribute in the button element. If there is no element then the printing functionality won’t work. We will wire to the button a click event handler which uses the printElement function to add the element that we want to print into the print section and then we use the window.print function to enable printing. Pay attention that we clone the DOM element that we want to print and then append the clone to the print section. We also make sure to clean the print section after printing occurred using the onafterprint event handler.

That is the part of the directive but we will need a little CSS magic to enable the print functionality.

The CSS Part

Once you have the directive in place, you will need the help of two media queries to achieve the printing functionality. If you just add the print section DIV without any CSS the whole web page will be printed. We want to print only the print section so here is a few lines of CSS that will help you to do that:

@media screen {
    #printSection {
        display: none;
    }
}

@media print {
    body * {
        visibility:hidden;
    }
    #printSection, #printSection * {
        visibility:visible;
    }
    #printSection {
        position:absolute;
        left:0;
        top:0;
    }
}

In the CSS, the printSection DIV is never shown on screen. Also, when printing occurs, the print media query will make sure not to display anything but the print section. It will also make sure that the print section is starting in the left top corner of the printing.

Using The Directive

After we added both the directive code and the CSS lets see how to use the directive:

<button class="btn btn-primary" ng-print print-element-id="printThisElement"><i class="fa fa-print"></i> Print</button>

In the button you will just put the ng-print directive and also the print-element-id attribute.

Summary

In the post I show a suggestion for a simple print button directive. Of course there are other ways to implement this functionality. 
Feel free to use this code or to update it to your own needs.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
dotnet ,javascript ,visual studio ,.net & windows ,angular ,web dev

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}