0

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?

  • [TextLayout](https://docs.oracle.com/en/java/javase/17/docs/api/java.desktop/java/awt/font/TextLayout.html) can do wrapping. – VGR Dec 15 '21 at 19:19

1 Answers1

0

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;
}
bradley101
  • 723
  • 6
  • 19
  • Thanks a lot, but as the elements are not fixed, I would prefer to use a loop, etc. On the other hand, I tried to format it using `jackson API`, but cannot format. I think we can fix the problem using it. Any idea? –  Dec 15 '21 at 18:21
  • You can convert that JSON string into a Map by using Gson very easily. Then loop through all the keys. https://stackoverflow.com/a/21720953/7373144 – bradley101 Dec 15 '21 at 18:23