Reputation: 23
I generated a Html with information of my client, so that he can attach them to your website or email. But some clients asked me to generate an image and not the html. I used the code below to generate the image, and it went well, but the image contained in the html is not being generated. When I open the HTML code in browser it works correctly, but when I generated the image from html, it generates only text and breaks the image.
public static void main(String[] args) throws Exception {
String html = "<body lang=PT-BR style='tab-interval:35.4pt'><img src='http://nxcache.nexon.net/all/v1.5.2/img/gnt/games-dropdown/maplestory.jpg'></body>";
int width = 600, height = 200;
BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleImage(width, height);
Graphics graphics = image.createGraphics();
JEditorPane jep = new JEditorPane("text/html", html);
jep.setSize(width, height);
jep.print(graphics);
ImageIO.write(image, "png", new File("C:\\Users\\MYUSER\\Documents\\NetBeansProjects\\HtmlToImage\\Image.png"));
Does anyone have any idea what might be happening?
This is my problem in picture. --> Erro
project on git: github
Upvotes: 2
Views: 26230
Reputation: 5384
Using java-html2image
(https://github.com/hkirk/java-html2image):
// pom.xml
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
...
<dependencies>
<dependency>
<groupId>com.github.hkirk</groupId>
<artifactId>java-html2image</artifactId>
<version>0.9</version>
</dependency>
</dependencies>
public void testing() {
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
imageGenerator.loadHtml("<body><span>Hello World!</span></body>");
imageGenerator.saveAsImage("testing.png");
}
The bad part of using java-html2image
is: the output image always has white borders (so having black background is impossible).
Updates:
I found the solution for the white border issue:
HtmlImageGenerator imageGenerator = new HtmlImageGenerator() {
protected JEditorPane createJEditorPane() {
JEditorPane editor = super.createJEditorPane();
editor.setOpaque(false); // The solution
return editor;
}
};
Now the output image is clear!
Upvotes: 4
Reputation: 2027
You can make use of this library https://code.google.com/archive/p/java-html2image/ which provides options to convert html to image.
Code will look something like this.
String html = "<body lang=PT-BR style='tab-interval:35.4pt'><img src='http://nxcache.nexon.net/all/v1.5.2/img/gnt/games-dropdown/maplestory.jpg'></body>";
HtmlImageGenerator hig = new HtmlImageGenerator();
hig.loadHtml(html);
hig.saveAsImage(new File("test.png"));
Upvotes: 3