1.需要的jar包; <!-- https://mvnrepository.com/artifact/gui.ava/html2image --> <dependency> <groupId>gui.ava</groupId> <artifactId>html2image</artifactId> <version>2.0.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.xhtmlrenderer/core-renderer --> <dependency> <groupId>org.xhtmlrenderer</groupId> <artifactId>core-renderer</artifactId> <version>R8</version> </dependency> <!-- https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml --> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency>
2.根据html代码转图片;
import gui.ava.html.parser.HtmlParser; import gui.ava.html.parser.HtmlParserImpl; import gui.ava.html.renderer.ImageRenderer; import gui.ava.html.renderer.ImageRendererImpl;
// public String html2Img(String html) { HtmlParser htmlParser = new HtmlParserImpl(); htmlParser.loadHtml(html); String filePath = tempPath + new Date().getTime() + ".png"; File parentPath = new File(tempPath); if (!parentPath.exists()) { parentPath.mkdirs(); } ImageRenderer imageRenderer = new ImageRendererImpl(htmlParser); imageRenderer.saveImage(filePath); return filePath; }