0

A mechanism for converting an HTML element to an image (e.g., PNG) is "rendering" it via a JEditorPane, as follows:

public void render(String html, int width, int height, file output) {
  JEditorPane jep = new JEditorPane("text/html", html);
  jep.setSize(width, height);
  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  jep.print(image.getGraphics());
  ImageIO.write(image, "PNG", output);
}

This approach works for simple HTML code, including basic support for CSS.

Is there any way to "autodetect" the width and height, instead of specifying it explicitly in the render() method?

Or any better way to convert HTML to an image, via "plain vanilla" Java?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
PNS
  • 19,295
  • 32
  • 96
  • 143

1 Answers1

1

Most of HTML element has no "default" size. Size are set by the text found into this element and the width of the screen where the element is displayed.

But, if you want to render an element with the current style displayed on the user screen, you can probably try to get the root element width.

For that, try to convert the HTML String to DOM Element (Creating a new DOM element from an HTML string using built-in DOM methods or Prototype) then, get the root element width and height.

Lucas Duval
  • 188
  • 1
  • 7