java在Linux平台调用标签打印机

java在Linux平台调用标签打印机

一.概述

Linux平台java调用标签打印机使用了开源框架cups4j,github下载地址:https://github.com/harwey/cups4j。 使用cups4j必须在电脑开启cups服务,且安装标签打印机驱动的情况下,其原理是通过连接cups服务调用打印打印功能,下面我们以兄弟打印机为例,演示linux平台java调用打印机功能。

二.示例

在github下载代码后,加入工程,demo代码如下

	 public static void main(String[] args) throws Exception {
	    	CupsClient client = getCupsClient();
	        List<CupsPrinter> printers = client.getPrinters(); //获取所有打印机
	        for (CupsPrinter p : printers) {
	        	if(p.getName().equalsIgnoreCase("PT-P900")){ //兄弟打印机名称
	        		System.out.println("Printer: " + p.toString());
	        		File file = new File("/home/test/pdf417.png"); //待打印图片位置
	                p.print(createPrintJob(file));//打印
					break;
	        	}	          
	        }
		}
	    
	    private static PrintJob createPrintJob(File file) {
	        return createPrintJob(file, CupsClient.DEFAULT_USER);
	    }
	    
	    private static String generateJobnameFor(File file) {
	        String basename = file.getName().split("\\.")[0];
	        return generateJobNameFor(basename);
	    }

	    private static String generateJobNameFor(String basename) {
	        byte[] epochTime = Base64.encodeBase64(BigInteger.valueOf(System.currentTimeMillis()).toByteArray());
	        return basename + new String(epochTime).substring(2);
	    }
	    
	    private static PrintJob createPrintJob(File file, String userName) {
	        String jobname = generateJobnameFor(file);
	        try {
	            byte[] content = FileUtils.readFileToByteArray(file);
	            return new PrintJob.Builder(content).jobName(jobname).userName(userName).build();
	        } catch (IOException ioe) {
	            throw new IllegalArgumentException("cannot read '" + file + "'", ioe);
	        }
	    }
	    
	    public static CupsClient getCupsClient() {
	        String host = System.getProperty("host", "127.0.0.1");
	        int port = Integer.parseInt(System.getProperty("port", "631"));
	        
	        try {
	          return new CupsClient(host, port);
	          
	        } catch (Exception ex) {
	          throw new IllegalStateException("cannot get CUPS client for " + host + ":" + port);
	        }
	      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值