i'm facing some problem converting html to image using java im using html2image[java]
it create an image, but the problem is it only create an image on a small part of the html. how can i make it to make an image of the whole html. thank you
this is my code
import gui.ava.html.image.generator.HtmlImageGenerator;
import java.io.File;
public class test {
public static void main(String[] args) {
HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
String uri = new File("C:\\cover.html").toURI().toString();
imageGenerator.loadUrl(uri);
imageGenerator.saveAsImage("hello-world.png");
imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");
}
}
i also use saveAsHtmlWithMap to save the html file. and that html file written by the program to the harddisk is also a small one.
this is the html code of cover.thml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="***">
<head>
<title></title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=1200, height=1200"/>
<link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body id="cover_page">
<nav id="cover" >
<ol>
<li id="nav1">
<a>cover</a>
</li>
</ol>
</nav>
</body>
</html>
HtmlImageGenerator by default creates and sets a java.awt.Dimension object of (800,800). You can pass your own new Dimension(x, y) of your custom size using below setter of HtmlImageGenerator class:
I hope it helps.
@Pralay, unfortunately,
imageGenerator.setSize(new Dimension(1024, 768));
and
imageGenerator.getDefaultSize().setSize(1024, 768);
didn't help.
Anyway, default size in
ImageRenderer
used by html2image is 1024x768. Look at the excerpt fromImageRendereImpl
class:But pay attention to the
autoHeight
field. Below insideImageRendererImpl
class you can see:If
authHeight
is true (actually it'strue
by default)getMinimumSize()
method oforg.xhtmlrenderer.simple.Graphics2DRenderer
class will be invoked. As can be concluded from the corresponding Javadoc the minimal possible area will be used. This is why you get too little image.Setting
autoHeight
tofalse
solves the issue:So I've got
PS: I've investigated and overcame the issue with aid of html2image v. 2.0-SNAPSHOT. As for v. 0.9 (which is in Maven Central) you need to modify the source code (v. 0.9 is old and not flexible).
PS2 In pure Java you can try something like this:
PS3 As I see html2image is not maintained now (in order to use to v. 2.0 you need to download and compile it by yourself). Perhaps, there are some living forks of this library. Or just try another HTML rendering library.
I am not experienced with html2image, but maybe it can parse the inline CSS only and that's the reason because the resulting image is not the same as is rendered in the browser.
Try adding an inline style with the contens of
main.css
to your HTML and save an image again.