js打印html页面中的指定内容?

【一起探讨,微信公众号:qdgithub】

js打印html页面中的指定内容?

文章发布日期: 2017-12-20
文章更新日期:2018-01-08 添加demo下载

下载地址

传送门->点击去下载

声明,所有的打印页面都叫,index.html

使用table2excel.js直接下载table数据到excel中

获取table2excel.js文件

github:table2excel.js点击去取

使用步骤

  1. 在html页面中引入jquery,版本要注意。

点开上面的链接,打开table2excel.jquery.json的文件,dependencies(依赖项)要求jquery>=1.4
所以呢,你需要有个jquery,并把它引入到index.html中。我使用的jquery版本是v1.11.3

  1. 网上随便找一个 table,顺手甩在index.html里。
 
This shouldn't get exportedThis shouldn't get exported either
This Should get exported as a headerThis should too
data1a with a link one and link two. data1b with a image.
data2a with a . data2b with a .
This footer spans 2 cells
  1. 在index.html里引入table2excel.js,然后调用,就可以下载了
$(function(){
  $(".table2excel").table2excel({
    exclude: ".noExl",
    name: "Excel Document Name",
    filename: "myFileName" + new Date().toISOString().replace(/[\-\:\.]/g, ""),
    fileext: ".xls",
    exclude_img: true,
    exclude_links: true,
    exclude_inputs: true
  });	
});

下载excel,简单实现,带源码,想看就看不看跳过

贴出源码

//打印表格
var idTmr;

function getExplorer() {
    var explorer = window.navigator.userAgent;
    if(explorer.indexOf("MSIE") >= 0) {
        return 'ie';
    }else if(explorer.indexOf("Firefox") >= 0) {
        return 'Firefox';
    }else if(explorer.indexOf("Chrome") >= 0) {
        return 'Chrome';
    }else if(explorer.indexOf("Opera") >= 0) {
        return 'Opera';
    }else if(explorer.indexOf("Safari") >= 0) {
        return 'Safari';
    }
}

function method5(tableid) {
    if(getExplorer() == 'ie') {
        var curTbl = document.getElementById(tableid);
        var oXL = new ActiveXObject("Excel.Application");
        var oWB = oXL.Workbooks.Add();
        var xlsheet = oWB.Worksheets(1);
        var sel = document.body.createTextRange();
        sel.moveToElementText(curTbl);
        sel.select();
        sel.execCommand("Copy");
        xlsheet.Paste();
        oXL.Visible = true;

        try {
            var fname = oXL.Application.GetSaveAsFilename("Excel.xls",
                "Excel Spreadsheets (*.xls), *.xls");
        } catch(e) {
            print("Nested catch caught " + e);
        } finally {
            oWB.SaveAs(fname);
            oWB.Close(savechanges = false);
            oXL.Quit();
            oXL = null;
            idTmr = window.setInterval("Cleanup();", 1);
        }

    } else {
        tableToExcel(tableid)
    }
}

function Cleanup() {
    window.clearInterval(idTmr);
    CollectGarbage();
}
var tableToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,',
        template = '{table}
', base64 = function( s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function(table, name) { if(!table.nodeType) table = document.getElementById(table) var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML } window.location.href = uri + base64(format(template, ctx)) } })()

使用步骤

直接调用method5()把table的id传进去
如:method5(‘dataTable’)

使用printArea打印table数据,调用浏览器自带打印设备可预览

使用步骤

  1. 引入jquery,布置好table

布局table时注意,如果想引入table的样式,需嘘嘘

XX市医疗保险特药使用申请表

申请单号 申请日期:XXX年XX月XX日
Info Header 1 Info Header 2 Info Header 3 Info Header 4 Info Header 5 Info Header 6 Info Header 7
Text 1A Text 1B Text 1C Text 1D Text 1E Text 1F Text 1G
Text 2A Text 2B Text 2C Text 2D Text 2E Text 2F Text 2G
Text 3A Text 3B Text 3C Text 3D Text 3E Text 3F Text 3G
  1. 获取jquery.printarea.js的源码,并引入

github:点击直达源码

如果使用这个三年前的源码有问题的话,比如打印空白,可以使用下面由其他网友提供的源码,地址见目录‘空白源码’

  1. 调用printArea()方法

printArea简单实现源码,想看就看,不看跳过

(function($) {
	
	var printAreaCount = 0;
	var removePrintArea = function(id) {
		$("iframe#" + id).remove();
	};
	
	$.fn.printArea = function() {
		var ele = $(this);
		var idPrefix = "printArea_";
		removePrintArea(idPrefix + printAreaCount);
		
		printAreaCount++;
		var iframeId = idPrefix + printAreaCount;
		var iframeStyle = 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;';
		iframe = document.createElement('IFRAME');
		$(iframe).attr({
			style: iframeStyle,
			id: iframeId
		});
		
		// 把iframe放到body中
		document.body.appendChild(iframe);
		
		// 获取iframe的document的属性
		var doc = iframe.contentWindow.document;
		doc.open(); // 开启
		
		// 获取当前窗口的css文件并引入到iframe中
		$(document).find("link").filter(function() {
			return $(this).attr("rel").toLowerCase() == "stylesheet";
		}).each(function() {
				doc.write('');
		});
		
		// 展示要打印的内容
		doc.write('
' + $(ele).html() + '
'); doc.close(); // 关闭 var frameWindow = iframe.contentWindow; frameWindow.close(); frameWindow.focus(); frameWindow.print(); } })(jQuery);

空白源码

(function($) {
	var counter = 0;
	var modes = {
		iframe: "iframe",
		popup: "popup"
	};
	var standards = {
		strict: "strict",
		loose: "loose",
		html5: "html5"
	};
	var defaults = {
		mode: modes.iframe,
		standard: standards.html5,
		popHt: 500,
		popWd: 400,
		popX: 200,
		popY: 200,
		popTitle: '',
		popClose: false,
		extraCss: '',
		extraHead: '',
		retainAttr: ["id", "class", "style"]
	};

	var settings = {}; //global settings

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

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

		settings.id = idPrefix + counter;

		var $printSource = $(this);

		var PrintAreaWindow = PrintArea.getPrintWindow();

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

		setTimeout(function() {
			PrintArea.print(PrintAreaWindow);
		}, 1000);
	};

	var PrintArea = {
		print: function(PAWindow) {
			var paWindow = PAWindow.win;

			$(PAWindow.doc).ready(function() {
				paWindow.focus();
				paWindow.print();

				if(settings.mode == modes.popup && settings.popClose)
					setTimeout(function() {
						paWindow.close();
					}, 2000);
			});
		},
		write: function(PADocument, $ele) {
			PADocument.open();
			PADocument.write(PrintArea.docType() + "" + PrintArea.getHead() + PrintArea.getBody($ele) + "");
			PADocument.close();
		},
		docType: function() {
			if(settings.mode == modes.iframe) return "";

			if(settings.standard == standards.html5) return "";

			var transitional = settings.standard == standards.loose ? " Transitional" : "";
			var dtd = settings.standard == standards.loose ? "loose" : "strict";

			return '';
		},
		getHead: function() {
			var extraHead = "";
			var links = "";

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

			$(document).find("link")
				.filter(function() { // Requirement:  element MUST have rel="stylesheet" to be considered in print document
					var relAttr = $(this).attr("rel");
					return($.type(relAttr) === 'undefined') == false && relAttr.toLowerCase() == 'stylesheet';
				})
				.filter(function() { // Include if media is undefined, empty, print or all
					var mediaAttr = $(this).attr("media");
					return $.type(mediaAttr) === 'undefined' || mediaAttr == "" || mediaAttr.toLowerCase() == 'print' || mediaAttr.toLowerCase() == 'all'
				})
				.each(function() {
					links += '';
				});
			if(settings.extraCss) settings.extraCss.replace(/([^,\s]+)/g, function(m) {
				links += ''
			});

			return "" + settings.popTitle + "" + extraHead + links + "";
		},
		getBody: function(elements) {
			var htm = "";
			var attrs = settings.retainAttr;
			elements.each(function() {
				var ele = PrintArea.getFormData($(this));

				var attributes = ""
				for(var x = 0; x < attrs.length; x++) {
					var eleAttr = $(ele).attr(attrs[x]);
					if(eleAttr) attributes += (attributes.length > 0 ? " " : "") + attrs[x] + "='" + eleAttr + "'";
				}

				htm += '
' + $(ele).html() + '
'; }); return "" + htm + ""; }, getFormData: function(ele) { var copy = ele.clone(); var copiedInputs = $("input,select,textarea", copy); $("input,select,textarea", ele).each(function(i) { var typeInput = $(this).attr("type"); if($.type(typeInput) === 'undefined') typeInput = $(this).is("select") ? "select" : $(this).is("textarea") ? "textarea" : ""; var copiedInput = copiedInputs.eq(i); if(typeInput == "radio" || typeInput == "checkbox") copiedInput.attr("checked", $(this).is(":checked")); else if(typeInput == "text" || typeInput == "") copiedInput.attr("value", $(this).val()); else if(typeInput == "select") $(this).find("option").each(function(i) { if($(this).is(":selected")) $("option", copiedInput).eq(i).attr("selected", true); }); else if(typeInput == "textarea") copiedInput.text($(this).val()); }); return copy; }, getPrintWindow: function() { switch(settings.mode) { case modes.iframe: var f = new PrintArea.Iframe(); return { win: f.contentWindow || f, doc: f.doc }; case modes.popup: var p = new PrintArea.Popup(); return { win: p, doc: p.doc }; } }, Iframe: function() { var frameId = settings.id; var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;right:0px;top:0px;'; var iframe; try { iframe = document.createElement('iframe'); document.body.appendChild(iframe); $(iframe).attr({ style: iframeStyle, id: frameId, src: "#" + new Date().getTime() }); iframe.doc = null; iframe.doc = iframe.contentDocument ? iframe.contentDocument : (iframe.contentWindow ? iframe.contentWindow.document : iframe.document); } catch(e) { throw e + ". iframes may not be supported in this browser."; } if(iframe.doc == null) throw "Cannot find document."; return iframe; }, Popup: function() { var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no"; windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt; windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=yes"; var newWin = window.open("", "_blank", windowAttr); newWin.doc = newWin.document; return newWin; } }; })(jQuery);

最后,甩一个printArea的demo,copy直接用,注意引入jquery




	
		
		
		
		Document
		
		

	

	

_____市医疗保险特药使用申请表

申请单号: 申请日期:XXX年XX月XX日
姓名 张三 性别 年龄 28
社会保障卡卡号 123456789 身份证号 412326499216452135
人员类别 职工医保 居民医保
参保属地 南京 联系电话 17312278695
工作单位 南京德益康有限公司
家庭住址 南京德益康有限公司
申请使用用品名称 沙丹红 疾病诊断 谈鸟病
指定医院 南京市红十字医院 责任医生 李建用
确诊时间 2017-12-17 身高(cm) 178
体重(kg) 60 BSA(m^2) 1.78
提供附件名称 CT报告 血常规报告 基因检测
申请人签字(患者本人):
    年    月    日
申请人签字(患者本人):
协助药房盖章:
    年    月    日
注:1、本表一式两份,协助药房、参保患者各持一份。
      2、需提供的材料:社会保障卡、患者近期一寸免冠彩照、门诊特定项目(门诊大病)证、相关医疗文书(基因检测(必要时)、病理诊断、影像报告、门诊病历、出院小结)等材料。
      3、本表私自涂改或复印无效。

最最后在贴一个比较好看的表格,不负责解决中文乱码

	

车间能源消耗比例

车间 产量 电量 单耗
109 13 1.34 213
109 13 1.34 213
109 13 1.34 213
109 13 1.34 213
109 13 1.34 213
109 13 1.34 213

你可能感兴趣的:(【JavaScript】)