Search code examples
javaspringtextgraphicsgraphics2d

Graphics2D: Draw multiple line string from JSON in Java


I use the following method to add text to my generated QR code:

private static void insertText(BufferedImage source, String text, int x, int y) {
    Graphics2D graph = source.createGraphics();
    graph.setFont(new Font("Arial", Font.PLAIN, 12));
    graph.setColor(Color.BLACK);
    graph.drawString(text, x, y);
}

It adds the given text to the top of QR code. However, I want to draw JSON key-value pair as shown below as text, but I cannot see a proper method of Graphics2D.

Instead of:

{ "id": 100, "name": "John", "surname": "Boython" }

I want to draw text as shown below:

id: 100
name: John
surname: Boython 

So, how can I do this? Also, is there a wrap property for the drawing text of Graphics2D?


Solution

  • You can add all the JSON elements to the Graphics2D object one by one.

    graph.drawString("id: " + json.get("id"), x, y);
    graph.drawString("name: " + json.get("name"), x, y + 20);
    graph.drawString("surname: " + json.get("surname"), x, y + 30);
    

    Assuming json is a Map, where you have the key value pairs. Or you can use any other library or class you like.

    Edit: You can convert the JSON string into a Map by using Gson very easily. Read this answer https://stackoverflow.com/a/21720953/7373144

    Answer in the above link:

    Map<String, Object> jsonMap = new Gson().fromJson(
        jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
    );
    

    After this you can loop through the keys

    int mHeight = y;
    for (Map.EntrySet<String, String> kv : jsonMap.entrySet()) {
        graph.drawString(kv.getKey() + ": " + kv.getValue(), x, mHeight + 10);
        mHeight += 10;
    }