ZPL API异常:输入含多标签的单段ZPL代码仅生成首个标签求助
解决ZPL API仅生成多标签ZPL代码中第一个标签的问题
你遇到的问题出在Labelary API的调用逻辑上:API URL末尾的labelIndex参数作用是指定返回ZPL代码中的单个标签,当前代码每次仅请求索引为labelIndex的标签,所以如果输入的ZPL包含多个标签,默认只会返回第一个(索引0)。
要批量生成输入ZPL中的所有标签,需要先统计输入ZPL里的标签总数,再循环遍历每个标签索引调用API。以下是修改后的实现:
修改后的代码
import java.io.File; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ZplLabelGenerator { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.println("Enter ZPL (type 'exit' to finish):"); String zpl = scanner.nextLine(); while (!zpl.equalsIgnoreCase("exit")) { // 统计ZPL中的标签数量(每个标签以^XA开头) int labelCount = countZplLabels(zpl); if (labelCount == 0) { System.out.println("No valid ZPL labels found in input."); // 读取下一段输入 System.out.println("Enter next ZPL (type 'exit' to finish):"); zpl = scanner.nextLine(); continue; } // 遍历每个标签索引,生成对应文件 for (int labelIndex = 0; labelIndex < labelCount; labelIndex++) { URI uri = URI.create("https://api.labelary.com/v1/printers/8dpmm/labels/3.93701x5.90551/" + labelIndex + "/"); HttpRequest request = HttpRequest.newBuilder(uri) .header("Accept", "application/pdf") .POST(HttpRequest.BodyPublishers.ofString(zpl)) .build(); HttpClient client = HttpClient.newHttpClient(); HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray()); byte[] body = response.body(); if (response.statusCode() == 200) { File file = new File("label_" + labelIndex + ".pdf"); Files.write(file.toPath(), body); System.out.println("Label_" + labelIndex + " created successfully."); } else { String errorMessage = new String(body, StandardCharsets.UTF_8); System.out.println("Failed to create label " + labelIndex + ": " + errorMessage); } } // 读取下一段输入 System.out.println("Enter next ZPL (type 'exit' to finish):"); zpl = scanner.nextLine(); } } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } } // 统计ZPL中的标签数量,基于^XA开头标识 private static int countZplLabels(String zpl) { Pattern pattern = Pattern.compile("\\^XA"); Matcher matcher = pattern.matcher(zpl); int count = 0; while (matcher.find()) { count++; } return count; } }
关键修改说明
- 新增
countZplLabels方法:通过正则表达式匹配ZPL中的^XA标签起始指令,统计输入ZPL中的总标签数 - 循环遍历每个标签索引:针对每个标签索引(从0到总标签数-1),分别调用API生成对应标签文件
- 增加无效输入判断:如果输入的ZPL中没有有效标签,直接提示并跳过
这样当你输入包含多个^XA...^XZ块的ZPL代码时,就能一次性生成所有标签的PDF文件了。
内容的提问来源于stack exchange,提问作者Ives Jundi
相关产品推荐
相关产品推荐

