lavkach3

Форк
0
/
jquery.PrintArea.js 
238 строк · 6.7 Кб
1
(function ($) {
2
  var counter = 0;
3
  var modes = { iframe: "iframe", popup: "popup" };
4
  var standards = { strict: "strict", loose: "loose", html5: "html5" };
5
  var defaults = {
6
    mode: modes.iframe,
7
    standard: standards.html5,
8
    popHt: 500,
9
    popWd: 400,
10
    popX: 200,
11
    popY: 200,
12
    popTitle: "",
13
    popClose: false,
14
    extraCss: "",
15
    extraHead: "",
16
    retainAttr: ["id", "class", "style"],
17
  };
18

19
  var settings = {}; //global settings
20

21
  $.fn.printArea = function (options) {
22
    $.extend(settings, defaults, options);
23

24
    counter++;
25
    var idPrefix = "printArea_";
26
    $("[id^=" + idPrefix + "]").remove();
27

28
    settings.id = idPrefix + counter;
29

30
    var $printSource = $(this);
31

32
    var PrintAreaWindow = PrintArea.getPrintWindow();
33

34
    PrintArea.write(PrintAreaWindow.doc, $printSource);
35

36
    setTimeout(function () {
37
      PrintArea.print(PrintAreaWindow);
38
    }, 1000);
39
  };
40

41
  var PrintArea = {
42
    print: function (PAWindow) {
43
      var paWindow = PAWindow.win;
44

45
      $(PAWindow.doc).ready(function () {
46
        paWindow.focus();
47
        paWindow.print();
48

49
        if (settings.mode == modes.popup && settings.popClose)
50
          setTimeout(function () {
51
            paWindow.close();
52
          }, 2000);
53
      });
54
    },
55
    write: function (PADocument, $ele) {
56
      PADocument.open();
57
      PADocument.write(
58
        PrintArea.docType() +
59
          "<html>" +
60
          PrintArea.getHead() +
61
          PrintArea.getBody($ele) +
62
          "</html>"
63
      );
64
      PADocument.close();
65
    },
66
    docType: function () {
67
      if (settings.mode == modes.iframe) return "";
68

69
      if (settings.standard == standards.html5) return "<!DOCTYPE html>";
70

71
      var transitional =
72
        settings.standard == standards.loose ? " Transitional" : "";
73
      var dtd = settings.standard == standards.loose ? "loose" : "strict";
74

75
      return (
76
        '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' +
77
        transitional +
78
        '//EN" "http://www.w3.org/TR/html4/' +
79
        dtd +
80
        '.dtd">'
81
      );
82
    },
83
    getHead: function () {
84
      var extraHead = "";
85
      var links = "";
86

87
      if (settings.extraHead)
88
        settings.extraHead.replace(/([^,]+)/g, function (m) {
89
          extraHead += m;
90
        });
91

92
      $(document)
93
        .find("link")
94
        .filter(function () {
95
          // Requirement: <link> element MUST have rel="stylesheet" to be considered in print document
96
          var relAttr = $(this).attr("rel");
97
          return (
98
            ($.type(relAttr) === "undefined") == false &&
99
            relAttr.toLowerCase() == "stylesheet"
100
          );
101
        })
102
        .filter(function () {
103
          // Include if media is undefined, empty, print or all
104
          var mediaAttr = $(this).attr("media");
105
          return (
106
            $.type(mediaAttr) === "undefined" ||
107
            mediaAttr == "" ||
108
            mediaAttr.toLowerCase() == "print" ||
109
            mediaAttr.toLowerCase() == "all"
110
          );
111
        })
112
        .each(function () {
113
          links +=
114
            '<link type="text/css" rel="stylesheet" href="' +
115
            $(this).attr("href") +
116
            '" >';
117
        });
118
      if (settings.extraCss)
119
        settings.extraCss.replace(/([^,\s]+)/g, function (m) {
120
          links += '<link type="text/css" rel="stylesheet" href="' + m + '">';
121
        });
122

123
      return (
124
        "<head><title>" +
125
        settings.popTitle +
126
        "</title>" +
127
        extraHead +
128
        links +
129
        "</head>"
130
      );
131
    },
132
    getBody: function (elements) {
133
      var htm = "";
134
      var attrs = settings.retainAttr;
135
      elements.each(function () {
136
        var ele = PrintArea.getFormData($(this));
137

138
        var attributes = "";
139
        for (var x = 0; x < attrs.length; x++) {
140
          var eleAttr = $(ele).attr(attrs[x]);
141
          if (eleAttr)
142
            attributes +=
143
              (attributes.length > 0 ? " " : "") +
144
              attrs[x] +
145
              "='" +
146
              eleAttr +
147
              "'";
148
        }
149

150
        htm += "<div " + attributes + ">" + $(ele).html() + "</div>";
151
      });
152

153
      return "<body>" + htm + "</body>";
154
    },
155
    getFormData: function (ele) {
156
      var copy = ele.clone();
157
      var copiedInputs = $("input,select,textarea", copy);
158
      $("input,select,textarea", ele).each(function (i) {
159
        var typeInput = $(this).attr("type");
160
        if ($.type(typeInput) === "undefined")
161
          typeInput = $(this).is("select")
162
            ? "select"
163
            : $(this).is("textarea")
164
            ? "textarea"
165
            : "";
166
        var copiedInput = copiedInputs.eq(i);
167

168
        if (typeInput == "radio" || typeInput == "checkbox")
169
          copiedInput.attr("checked", $(this).is(":checked"));
170
        else if (typeInput == "text") copiedInput.attr("value", $(this).val());
171
        else if (typeInput == "select")
172
          $(this)
173
            .find("option")
174
            .each(function (i) {
175
              if ($(this).is(":selected"))
176
                $("option", copiedInput).eq(i).attr("selected", true);
177
            });
178
        else if (typeInput == "textarea") copiedInput.text($(this).val());
179
      });
180
      return copy;
181
    },
182
    getPrintWindow: function () {
183
      switch (settings.mode) {
184
        case modes.iframe:
185
          var f = new PrintArea.Iframe();
186
          return { win: f.contentWindow || f, doc: f.doc };
187
        case modes.popup:
188
          var p = new PrintArea.Popup();
189
          return { win: p, doc: p.doc };
190
      }
191
    },
192
    Iframe: function () {
193
      var frameId = settings.id;
194
      var iframeStyle =
195
        "border:0;position:absolute;width:0px;height:0px;right:0px;top:0px;";
196
      var iframe;
197

198
      try {
199
        iframe = document.createElement("iframe");
200
        document.body.appendChild(iframe);
201
        $(iframe).attr({
202
          style: iframeStyle,
203
          id: frameId,
204
          src: "#" + new Date().getTime(),
205
        });
206
        iframe.doc = null;
207
        iframe.doc = iframe.contentDocument
208
          ? iframe.contentDocument
209
          : iframe.contentWindow
210
          ? iframe.contentWindow.document
211
          : iframe.document;
212
      } catch (e) {
213
        throw e + ". iframes may not be supported in this browser.";
214
      }
215

216
      if (iframe.doc == null) throw "Cannot find document.";
217

218
      return iframe;
219
    },
220
    Popup: function () {
221
      var windowAttr =
222
        "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
223
      windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
224
      windowAttr +=
225
        ",resizable=yes,screenX=" +
226
        settings.popX +
227
        ",screenY=" +
228
        settings.popY +
229
        ",personalbar=no,scrollbars=yes";
230

231
      var newWin = window.open("", "_blank", windowAttr);
232

233
      newWin.doc = newWin.document;
234

235
      return newWin;
236
    },
237
  };
238
})(jQuery);
239

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.