引言
项目中要用到生成一系列的条形码,并在网页中打印
前端用的是Angular2,在实现的过程中查找了许多资料,以下是相关总结
步骤
1.下载JsBarcode.all.js
下载地址:/download/francis123580/10130270
2.把JsBarcode引入到项目
首先把js放在assets文件夹下;
然后在index.html中引入;
最后在用到的组件中声明:declare var JsBarcode: any;
参考博客:如何在Angular2中使用jQuery及其插件的方法
、 Angular2中如何使用jquery 、 在 Angular 2 Component 中使用第三方 JS 库
3.编写生成条形码的代码
html code
<div id="print-section"><div *ngFor="let bc of barcodeList;let i=index" style="float:left;width:33%;margin-top:10px"><div style="text-align:center">{{barcodeTitle}}</div><div style="text-align:center"> <img id="bc_{{i}}"/></div></div></div>
ts code
import { Component, OnInit } from '@angular/core';declare var JsBarcode: any;const STRINGLIST: string[] = ["14221345", "1543253452", "312542345", "3154346543", "14221345", "1543253452", "312542345", "3154346543"];@Component({selector: 'print-page',templateUrl: './print-ponent.html',styleUrls: ['./print-ponent.css']})export class PrintPageComponent implements OnInit {public barcodeList: string[] = STRINGLIST;public barcodeTitle:string="图书馆";constructor() { }ngOnInit() {setTimeout(() => {for (var i = 0; i < this.barcodeList.length; i++) {this.generateBarcode("bc_" + i, this.barcodeList[i]);}}, 1000);}/* 生成条形码 */generateBarcode(id: string, code: string) {var barcode = document.getElementById(id),options = {format: "CODE128",displayValue: true,fontSize: 18,height: 100};JsBarcode(barcode, code, options);}}
参考博客:条形码插件-JsBarcode的使用 、jquery-barcode:js实现的条码打印 、JSBarcode
4.编写打印页面的代码
html code
<div style="width: 100%;float: left;text-align: center;margin-top: 30px;"><button style="font-size:20px" (click)="print()">打印</button></div>
ts code
/* 打印 */print(): void {let printContents, popupWin;printContents = document.getElementById('print-section').innerHTML;popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');popupWin.document.open();popupWin.document.write(`<html><head><title>Print Page</title><style>//........Customized style.......</style></head><body onload="window.print();window.close()">${printContents}</body></html>`);popupWin.document.close();}
小结
因为这是一个测试组件,所以用的数据是const假数据,相关的数据格式和内容需要根据自己的后端接口返回的数据来重新编写
另外需要注意一下异步的问题,不然会报getContext的问题,建议返回数据之后再做页面的渲染,渲染完成之后再生成条形码
如果觉得《【Angular2】生成条形码并打印网页》对你有帮助,请点赞、收藏,并留下你的观点哦!