背景

最新一个项目上涉及到生成条形码,并打印出来,个人经常写java,但是用后端去处理这个反而挺麻烦的。使用js是比较方便的,这里就简单地介绍一下。
在网上查了很多关于生成条形码的内容,就属JsBarcode用的最好,github地址:https://github/lindell/JsBarcode。对于生成条形码的延申,也可以好好查看。

使用环境

这个JsBarcode 的js插件式依赖于jquery库,你需要先把这个导入,然后再导入JsBarcode库。否则会出问题。

代码详解

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<script type="text/javascript" src="js/jquery2.1.4.min.js"></script>
<script type="text/javascript" src="js/JsBarcode.all.min.js"></script>
<script type="text/javascript">
	function myprint(){ 
	  //直接调用浏览器打印功能
	   bdhtml=window.document.body.innerHTML; 
	   //定义打印区域起始字符,根据这个截取网页局部内容     
	   sprnstr="<!--startprint-->"; //打印区域开始的标记
	   eprnstr="<!--endprint-->";   //打印区域结束的标记  
	   prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);      
	   prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));     
	   window.document.body.innerHTML=prnhtml;   
	   //开始打印
	   window.print();
	   //还原网页内容     
	   window.document.body.innerHTML=bdhtml; 
	}
	function barcodeGen(){
    	var barvalue=$("#barcodeValue").val();
    	if(barvalue==""){
    		alert("请输入条形码字符串!!")
    	}else{
        	$("#bcode").JsBarcode(barvalue);
    	}
	}
</script>
<body>
	<hr>
	请输入要转成条形码的数字:<input type="text"  id="barcodeValue"> &nbsp;<a href="#" onClick="barcodeGen();" ><span> 生成条形码</span></a><br>
    <!--startprint-->
    <img id="bcode"/>
    <!--endprint-->
    <hr>
    <a href="#" onClick="myprint();" ><span> 打  印</span></a><br>
</body>
</html>

效果演示

程序源码:在我的订阅号(Name:皮皮总; ID:pipizongITR ;左侧二维码)中回复:“printbarcode”即可。

更多推荐

Jquery生成条形码到网页以及打印条形码