斑马打印机浏览器打印

子车灿
2023-12-01
<html>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<head>
<script type="text/javascript" src="js/BrowserPrint-3.0.216.js"></script>
<script type="text/javascript" src="js/html2canvas.min.js"></script>
<script type="text/javascript" src="js/Changpdi.js"></script>
<script type="text/javascript">
var selected_device;
var devices = [];

function setup()
{
	//Get the default device from the application as a first step. Discovery takes longer to complete.
	BrowserPrint.getDefaultDevice("printer", function(device)
			{
		
				//Add device to list of devices and to html select element
				selected_device = device;
				devices.push(device);
				var html_select = document.getElementById("selected_device");
				var option = document.createElement("option");
				option.text = device.name;
				html_select.add(option);
				
				//Discover any other devices available to the application
				BrowserPrint.getLocalDevices(function(device_list){
					for(var i = 0; i < device_list.length; i++)
					{
						//Add device to list of devices and to html select element
						var device = device_list[i];
						if(!selected_device || device.uid != selected_device.uid)
						{
							devices.push(device);
							var option = document.createElement("option");
							option.text = device.name;
							option.value = device.uid;
							html_select.add(option);
						}
					}
					
				}, function(){alert("Error getting local devices")},"printer");
				
			}, function(error){
				alert(error);
			})
}
function getConfig(){
	BrowserPrint.getApplicationConfiguration(function(config){
		alert(JSON.stringify(config))
	}, function(error){
		alert(JSON.stringify(new BrowserPrint.ApplicationConfiguration()));
	})
}
function writeToSelectedPrinter(dataToWrite)
{
	selected_device.send(dataToWrite, undefined, errorCallback);
}
var readCallback = function(readData) {
	if(readData === undefined || readData === null || readData === "")
	{
		alert("No Response from Device");
	}
	else
	{
		alert(readData);
	}
	
}
var errorCallback = function(errorMessage){
	alert("Error: " + errorMessage);	
}
function readFromSelectedPrinter()
{

	selected_device.read(readCallback, errorCallback);
	
}
function getDeviceCallback(deviceList)
{
	alert("Devices: \n" + JSON.stringify(deviceList, null, 4))
}

function sendImage(imageUrl)
{
	//url = window.location.href.substring(0, window.location.href.lastIndexOf("/"));
	//url = url + "/" + imageUrl;
	selected_device.convertAndSendFile(imageUrl, undefined, errorCallback)
}
function getPixelRatio(context){
  var backingStore = context.backingStorePixelRatio ||
    context.webkitBackingStorePixelRatio ||
    context.mozBackingStorePixelRatio ||
    context.msBackingStorePixelRatio ||
    context.oBackingStorePixelRatio ||
    context.backingStorePixelRatio || 1;
  return (window.devicePixelRatio || 1) / backingStore;
}
function sendImage2()
{
  var shareContent = document.querySelector('.tqf');// 需要绘制的部分的 (原生)dom 对象 ,注意容器的宽度不要使用百分比,使用固定宽度,避免缩放问题
  var width = shareContent.offsetWidth;  // 获取(原生)dom 宽度
  var height = shareContent.offsetHeight; // 获取(原生)dom 高
  var offsetTop = shareContent.offsetTop;  //元素距离顶部的偏移量
  var canvas = document.createElement('canvas');  //创建canvas 对象
  var context = canvas.getContext('2d');
   var scaleBy = 300 / 96; //获取像素密度的方法 (也可以采用自定义缩放比例)
  // var scaleBy = getPixelRatio(context);  //获取像素密度的方法 (也可以采用自定义缩放比例)
  canvas.width =  (height + offsetTop) * scaleBy;  //这里 由于绘制的dom 为固定宽度,居中,所以没有偏移
   canvas.height = width * scaleBy;  // 注意高度问题,由于顶部有个距离所以要加上顶部的距离,解决图像高度偏移问题
  //context.scale(scaleBy, scaleBy);
  // setDPI(canvas,300)
  var opts = {
    userCORS:true,
    allowTaint:true,//允许加载跨域的图片
    tainttest:true, //检测每张图片都已经加载完成
    scale:scaleBy, // 添加的scale 参数
    canvas:canvas, //自定义 canvas
    logging: true, //日志开关,发布的时候记得改成false
    width:canvas.width, //dom 原始宽度
    height:canvas.height //dom 原始高度
  };
  // var showImg = document.querySelector(".canvas");
  html2canvas(document.querySelector("#capture"),opts).then(function (canvas)  {
    //console.log("canvas", canvas);
    // document.body.appendChild(canvas)
    console.log(canvas);
    //canvas.width = "16cm";
    //canvas.width = "10cm";
    //let height =  "10cm";
    //let width = "16cm";
   // canvas.style = `width:${width};height:${height};position:fixed;z-index:9999;`;
    // 显示图片
    // 新增代码 返回图片的URL,设置为png格式。dataUrl是一个base64编码的图片URL地址

    dataUrl = canvas.toDataURL("image/png");
    console.log(dataUrl)
    // const blob = this.base64ImgtoFile(dataUrl)
    // const blobUrl = window.URL.createObjectURL(blob);
    const blob = this.base64ImgtoFile(dataUrl)

    const blobUrl = window.URL.createObjectURL(blob);
    // 这里的文件名根据实际情况从响应头或者url里获取
    const filename = blob.name;
    const a = document.createElement('a');
    a.href = dataUrl;
    a.download = filename;;
    a.click();
    //window.URL.revokeObjectURL(blobUrl);
    //sendImage(dataUrl)
    //console.log(dataUrl);
    //sendImage(blobUrl);
    //showImg.setAttribute("src", dataUrl);

    // 自动下载图片
    //var downloadUrl = dataUrl.replace("image/png", "image/octet-stream"); //图片地址
    //sendImage(downloadUrl)
    //console.log(downloadUrl);
     //window.location.href = downloadUrl; // 跳转下载
    // document.body.appendChild(canvas)
  });
}
function setDPI(canvas, dpi) {
  // Set up CSS size.
  canvas.style.width = canvas.style.width || canvas.width + 'px';
  canvas.style.height = canvas.style.height || canvas.height + 'px';

  // Resize canvas and scale future draws.
  var scaleFactor = dpi / 96;
  canvas.width = Math.ceil(canvas.width * scaleFactor);
  canvas.height = Math.ceil(canvas.height * scaleFactor);
  var ctx = canvas.getContext('2d');
  ctx.scale(scaleFactor, scaleFactor);
}
function base64ImgtoFile (dataurl, filename = 'file') {
  //将base64格式分割:['data:image/png;base64','XXXX']
  const arr = dataurl.split(',')
  // .*? 表示匹配任意字符到下一个符合条件的字符 刚好匹配到:
  // image/png
  const mime = arr[0].match(/:(.*?);/)[1]  //image/png
  //[image,png] 获取图片类型后缀
  const suffix = mime.split('/')[1] //png
  const bstr = atob(arr[1])   //atob() 方法用于解码使用 base-64 编码的字符串
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], `${filename}.${suffix}`, {
    type: mime
  })
}
function sendFile(fileUrl){
    url = window.location.href.substring(0, window.location.href.lastIndexOf("/"));
    url = url + "/" + fileUrl;
    selected_device.sendFile(url, undefined, errorCallback)
}
function onDeviceSelected(selected)
{
	for(var i = 0; i < devices.length; ++i){
		if(selected.value == devices[i].uid)
		{
			selected_device = devices[i];
			return;
		}
	}
}
window.onload = setup;
</script>
</head>
<body>
<div id="capture" class="tqf" style="border: 2px solid black;height: 10cm;width: 16cm;padding: 0.5cm 0.5cm 0cm 0.5cm;transform: rotate(90deg)">
  <table  cellspacing="0" style="border: 2px solid black;width: 100%">
    <tbody>
    <tr style="height: 1cm">
      <td colspan="3" style="border-bottom: 1px solid black;">Packing Label       AscenPower(Made in China)             RoHs COMPLIANT                      FAB 1</td>
    </tr>
    <tr style="height: 0.8cm">
      <td style="border-right: 1px solid black;">Frontend PartID:</td>
      <td style="border-right: 1px solid black;">Customer PartID:</td>
      <td>Sample/Waive:</td>
    </tr>
    <tr style="text-align: center;height: 0.8cm">
      <td style="text-align: center;border-bottom: 1px solid black;border-right: 1px solid black;" >123xxxxxx</td>
      <td style="text-align: center;border-bottom: 1px solid black;border-right: 1px solid black;" >c1234dddd</td>
      <td style="text-align: center;border-bottom: 1px solid black;" >s1234dddd</td>
    </tr>
    <tr style="height: 0.8cm">
      <td style="border-right: 1px solid black;">Frontend LotID:</td>
      <td style="border-right: 1px solid black;">Customer LotID:</td>
      <td>Packing Method:</td>
    </tr>
    <tr style="text-align: center;height: 0.8cm">
      <td style="text-align: center;border-bottom: 1px solid black;border-right: 1px solid black;" >123xxxxxx</td>
      <td style="text-align: center;border-bottom: 1px solid black;border-right: 1px solid black;" >c1234dddd</td>
      <td style="text-align: center;border-bottom: 1px solid black;" >s1234dddd</td>
    </tr>
    <tr style="height: 0.8cm">
      <td style="border-right: 1px solid black;">Backend PartID:</td>
      <td style="border-right: 1px solid black;">Lot Type:</td>
      <td rowspan="4"></td>
    </tr>
    <tr style="text-align: center;height: 0.8cm">
      <td style="text-align: center;border-bottom: 1px solid black;border-right: 1px solid black;" >123xxxxxx</td>
      <td style="text-align: center;border-bottom: 1px solid black;border-right: 1px solid black;" >c1234dddd</td>
    </tr>
    <tr style="height: 0.8cm">
      <td style="border-right: 1px solid black;">Backend LotID:</td>
      <td style="border-right: 1px solid black;">WaferQty:</td>
    </tr>
    <tr style="text-align: center;height: 0.8cm">
      <td style="text-align: center;border-right: 1px solid black;" >123xxxxxx</td>
      <td style="text-align: center;border-right: 1px solid black;" >c1234dddd</td>
    </tr>
    </tbody>
  </table>
  <table  cellspacing="0" style="border: 2px solid black;width: 100%;margin-top: 0.3cm">
    <tr style="height: 1cm">
      <td colspan="3">Packing Label               RoHs COMPLIANT                      FAB 1</td>
    </tr>
  </table>
  <table  cellspacing="0" style="width: 100%; table-layout: fixed;text-align: center">
    <tr style="height: 1cm">
      <td></td>
      <td>Date:2023/2/17</td>
      <td>QA PASS</td>
    </tr>
  </table>
</div>
<img src="" class="canvas" />
<span style="padding-right:50px; font-size:200%">Zebra Browser Print Test Page</span><br/>
<span style="font-size:75%">This page must be loaded from a web server to function properly.</span><br><br>
Selected Device: <select id="selected_device" onchange=onDeviceSelected(this);></select> <!--  <input type="button" value="Change" onclick="changeDevice();">--> <br/><br/>
<input type="button" value="Send html2canvas" onclick="sendImage2('ZebraGray.jpg');"><br/><br/>
<input type="button" value="Get Application Configuration" onclick="getConfig()"><br/><br/>
<input type="button" value="Send Config Label" onclick="writeToSelectedPrinter('~wc')"><br/><br/>
<input type="button" value="Send ZPL Label" onclick="writeToSelectedPrinter('^XA^FO200,200^A0N36,36^FDTest Label^FS^XZ')"><br/><br/>
<input type="button" value="Get Status" onclick="writeToSelectedPrinter('~hs'); readFromSelectedPrinter()"><br/><br/>
<input type="button" value="Get Local Devices" onclick="BrowserPrint.getLocalDevices(getDeviceCallback, errorCallback);"><br/><br/>
<input type="text" name="write_text" id="write_text"><input type="button" value="Write" onclick="writeToSelectedPrinter(document.getElementById('write_text').value)"><br/><br/>
<input type="button" value="Read" onclick="readFromSelectedPrinter()"><br/><br/>
<input type="button" value="Send BMP" onclick="sendImage('Zebra_logobox.bmp');"><br/><br/>
<input type="button" value="Send JPG" onclick="sendImage('ZebraGray.jpg');"><br/><br/>
<input type="button" value="Send File" onclick="sendFile('wc.zpl');"><br/><br/>
</body>
</html>

 类似资料: