Search code examples
javazpl

ZPL API not generating multiple labels


I am trying to generate multiple labels by adding only one ZPL code with multiple labels on it, but when I input the ZPL code, it generates only the first one. Help me please

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter ZPL (type 'exit' to finish):");
            String zpl = scanner.nextLine();
            int labelIndex = 0; // Start with label index 0

            while (!zpl.equalsIgnoreCase("exit")) {
                // Adjust print density (8dpmm), label width (4 inches), label height (6 inches), and label index as necessary
                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") // omit this line to get PNG images back
                        .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"); // Change file name for PNG images
                    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: " + errorMessage);
                }

                // Read the next ZPL input
                System.out.println("Enter next ZPL (type 'exit' to finish):");
                zpl = scanner.nextLine();
                labelIndex++; // Increment label index for the next label
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }

Solution

  • You're adding the index to the URL. From testing the API, even if you pass multiple ZPLs, it will only return the first one for index 0, second one for index 1 and so forth.

    If you can generate just 1 file for all of the labels, simply remove the index from the URL.

    If you wanna generate 1 file for each label, however, you have to either:

    • Iterate through each label individually, rather than going through all at once.
    • Get the quantity of labels you have on your zpl and call this API multiple times with this quantity.

    Be wary of the rate limit, though. Please refer to their API documentation at https://labelary.com/service.html#limits