jqprint.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import $ from 'jquery';
  2. (function ($) {
  3. var opt;
  4. $.fn.jqprint = function (options) {
  5. opt = $.extend({}, $.fn.jqprint.defaults, options);
  6. var $element = (this instanceof $) ? this : $(this);
  7. if (opt.operaSupport && $.browser.opera) {
  8. var tab = window.open("", "jqPrint-preview");
  9. tab.document.open();
  10. var doc = tab.document;
  11. }else {
  12. var $iframe = $("<iframe />");
  13. if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-300px", top: "-300px" }); }
  14. $iframe.appendTo("body");
  15. var doc = $iframe[0].contentWindow.document;
  16. }
  17. if (opt.importCSS) {
  18. doc.write('<!DOCTYPE html>');
  19. $("style").each(function () {//获取内联样式放到iframe中
  20. doc.write('<style type="text/css" rel="stylesheet" media="print" >' + $(this)[0].textContent + '</style>');
  21. });
  22. if ($("link[media=print]").length > 0) {//外联样式获取
  23. $("link[media=print]").each(function () {
  24. doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
  25. });
  26. }
  27. else {
  28. $("link").each(function () {
  29. doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
  30. });
  31. }
  32. }
  33. // var canvasLis = $(this).find('canvas');//页面有canvas需要转换为图片
  34. // if (!canvasLis) {
  35. // return
  36. // } else {
  37. // $("img").remove('.canvasImg')//删除已添加的图片避免多张图片重叠
  38. // for (var k = 0; k < canvasLis.length; k++) {
  39. // var canvas = canvasLis[k];
  40. // var canvasSrc = canvas.toDataURL();
  41. // let canvasImg = "<img class='canvasImg' src='" + canvasSrc + "'>"
  42. // $(canvasLis[k]).parent().append(canvasImg)
  43. // }
  44. // }
  45. if (opt.printContainer) { doc.write($element.outer()); }
  46. else { $element.each(function () { doc.write($(this).html()); }); }
  47. doc.close();
  48. (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
  49. setTimeout(function () { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 500);
  50. }
  51. $.fn.jqprint.defaults = {
  52. debug: false,
  53. importCSS: true,
  54. printContainer: true,
  55. operaSupport: true
  56. };
  57. $.fn.outer = function () {
  58. return $($('<div></div>').html(this.clone())).html();
  59. }
  60. })($);