Subversion-Projekte lars-tiefland.ci

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
875 lars 1
/*
2
 * printThis v1.5
3
 * @desc Printing plug-in for jQuery
4
 * @author Jason Day
5
 *
6
 * Resources (based on) :
7
 *              jPrintArea: http://plugins.jquery.com/project/jPrintArea
8
 *              jqPrint: https://github.com/permanenttourist/jquery.jqprint
9
 *              Ben Nadal: http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm
10
 *
11
 * Licensed under the MIT licence:
12
 *              http://www.opensource.org/licenses/mit-license.php
13
 *
14
 * (c) Jason Day 2014
15
 *
16
 * Usage:
17
 *
18
 *  $("#mySelector").printThis({
19
 *      debug: false,               * show the iframe for debugging
20
 *      importCSS: true,            * import page CSS
21
 *      importStyle: false,         * import style tags
22
 *      printContainer: true,       * grab outer container as well as the contents of the selector
23
 *      loadCSS: "path/to/my.css",  * path to additional css file - us an array [] for multiple
24
 *      pageTitle: "",              * add title to print page
25
 *      removeInline: false,        * remove all inline styles from print elements
26
 *      printDelay: 333,            * variable print delay
27
 *      header: null,               * prefix to html
28
 *      formValues: true            * preserve input/form values
29
 *  });
30
 *
31
 * Notes:
32
 *  - the loadCSS will load additional css (with or without @media print) into the iframe, adjusting layout
33
 */
34
;
35
(function($) {
36
    var opt;
37
    $.fn.printThis = function(options) {
38
        opt = $.extend({}, $.fn.printThis.defaults, options);
39
        var $element = this instanceof jQuery ? this : $(this);
40
 
41
        var strFrameName = "printThis-" + (new Date()).getTime();
42
 
43
        if (window.location.hostname !== document.domain && navigator.userAgent.match(/msie/i)) {
44
            // Ugly IE hacks due to IE not inheriting document.domain from parent
45
            // checks if document.domain is set by comparing the host name against document.domain
46
            var iframeSrc = "javascript:document.write(\"<head><script>document.domain=\\\"" + document.domain + "\\\";</script></head><body></body>\")";
47
            var printI = document.createElement('iframe');
48
            printI.name = "printIframe";
49
            printI.id = strFrameName;
50
            printI.className = "MSIE";
51
            document.body.appendChild(printI);
52
            printI.src = iframeSrc;
53
 
54
        } else {
55
            // other browsers inherit document.domain, and IE works if document.domain is not explicitly set
56
            var $frame = $("<iframe id='" + strFrameName + "' name='printIframe' />");
57
            $frame.appendTo("body");
58
        }
59
 
60
 
61
        var $iframe = $("#" + strFrameName);
62
 
63
        // show frame if in debug mode
64
        if (!opt.debug) $iframe.css({
65
            position: "absolute",
66
            width: "0px",
67
            height: "0px",
68
            left: "-600px",
69
            top: "-600px"
70
        });
71
 
72
 
73
        // $iframe.ready() and $iframe.load were inconsistent between browsers
74
        setTimeout(function() {
75
 
76
            var $doc = $iframe.contents(),
77
                $head = $doc.find("head"),
78
                $body = $doc.find("body");
79
 
80
            // add base tag to ensure elements use the parent domain
81
            $head.append('<base href="' + document.location.protocol + '//' + document.location.host + '">');
82
 
83
            // import page stylesheets
84
            if (opt.importCSS) $("link[rel=stylesheet]").each(function() {
85
                var href = $(this).attr("href");
86
                if (href) {
87
                    var media = $(this).attr("media") || "all";
88
                    $head.append("<link type='text/css' rel='stylesheet' href='" + href + "' media='" + media + "'>")
89
                }
90
            });
91
 
92
            // import style tags
93
            if (opt.importStyle) $("style").each(function() {
94
                $(this).clone().appendTo($head);
95
                //$head.append($(this));
96
            });
97
 
98
            //add title of the page
99
            if (opt.pageTitle) $head.append("<title>" + opt.pageTitle + "</title>");
100
 
101
            // import additional stylesheet(s)
102
            if (opt.loadCSS) {
103
               if( $.isArray(opt.loadCSS)) {
104
                    jQuery.each(opt.loadCSS, function(index, value) {
105
                       $head.append("<link type='text/css' rel='stylesheet' href='" + this + "'>");
106
                    });
107
                } else {
108
                    $head.append("<link type='text/css' rel='stylesheet' href='" + opt.loadCSS + "'>");
109
                }
110
            }
111
 
112
            // print header
113
            if (opt.header) $body.append(opt.header);
114
 
115
            // grab $.selector as container
116
            if (opt.printContainer) $body.append($element.outer());
117
 
118
            // otherwise just print interior elements of container
119
            else $element.each(function() {
120
                $body.append($(this).html());
121
            });
122
 
123
            // capture form/field values
124
            if (opt.formValues) {
125
                // loop through inputs
126
                var $input = $element.find('input');
127
                if ($input.length) {
128
                    $input.each(function() {
129
                        var $this = $(this),
130
                            $name = $(this).attr('name'),
131
                            $checker = $this.is(':checkbox') || $this.is(':radio'),
132
                            $iframeInput = $doc.find('input[name="' + $name + '"]'),
133
                            $value = $this.val();
134
 
135
                        //order matters here
136
                        if (!$checker) {
137
                            $iframeInput.val($value);
138
                        } else if ($this.is(':checked')) {
139
                            if ($this.is(':checkbox')) {
140
                                $iframeInput.attr('checked', 'checked');
141
                            } else if ($this.is(':radio')) {
142
                                $doc.find('input[name="' + $name + '"][value=' + $value + ']').attr('checked', 'checked');
143
                            }
144
                        }
145
 
146
                    });
147
                }
148
 
149
                //loop through selects
150
                var $select = $element.find('select');
151
                if ($select.length) {
152
                    $select.each(function() {
153
                        var $this = $(this),
154
                            $name = $(this).attr('name'),
155
                            $value = $this.val();
156
                        $doc.find('select[name="' + $name + '"]').val($value);
157
                    });
158
                }
159
 
160
                //loop through textareas
161
                var $textarea = $element.find('textarea');
162
                if ($textarea.length) {
163
                    $textarea.each(function() {
164
                        var $this = $(this),
165
                            $name = $(this).attr('name'),
166
                            $value = $this.val();
167
                        $doc.find('textarea[name="' + $name + '"]').val($value);
168
                    });
169
                }
170
            } // end capture form/field values
171
 
172
            // remove inline styles
173
            if (opt.removeInline) {
174
                // $.removeAttr available jQuery 1.7+
175
                if ($.isFunction($.removeAttr)) {
176
                    $doc.find("body *").removeAttr("style");
177
                } else {
178
                    $doc.find("body *").attr("style", "");
179
                }
180
            }
181
 
182
            setTimeout(function() {
183
                if ($iframe.hasClass("MSIE")) {
184
                    // check if the iframe was created with the ugly hack
185
                    // and perform another ugly hack out of neccessity
186
                    window.frames["printIframe"].focus();
187
                    $head.append("<script>  window.print(); </script>");
188
                } else {
189
                    // proper method
190
                    $iframe[0].contentWindow.focus();
191
                    $iframe[0].contentWindow.print();
192
                }
193
 
194
                //remove iframe after print
195
                if (!opt.debug) {
196
                    setTimeout(function() {
197
                        $iframe.remove();
198
                    }, 1000);
199
                }
200
 
201
            }, opt.printDelay);
202
 
203
        }, 333);
204
 
205
    };
206
 
207
    // defaults
208
    $.fn.printThis.defaults = {
209
        debug: false,           // show the iframe for debugging
210
        importCSS: true,        // import parent page css
211
        importStyle: false,     // import style tags
212
        printContainer: true,   // print outer container/$.selector
213
        loadCSS: "",            // load an additional css file - load multiple stylesheets with an array []
214
        pageTitle: "",          // add title to print page
215
        removeInline: false,    // remove all inline styles
216
        printDelay: 333,        // variable print delay
217
        header: null,           // prefix to html
218
        formValues: true        // preserve input/form values
219
    };
220
 
221
    // $.selector container
222
    jQuery.fn.outer = function() {
223
        return $($("<div></div>").html(this.clone())).html()
224
    }
225
})(jQuery);