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);
}
}