HTML转图片-JAVA

依赖组件

<dependency>
	<groupId>gui.ava</groupId>
	<artifactId>html2image</artifactId>
	<version>0.9</version>
</dependency>

示例

HtmlImageGenerator generator = new HtmlImageGenerator();
generator.loadHtml("<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\" style=\"font-size:24px\">Google</a>.");
// 如果HTML需要加载图片,需要睡眠,
//  图片src不支持相对路径,也不支持base64,必须加上file:/// 或者直接写http的url
ThreadUtil.sleep(500);
// 某些格式生成是黑的 不行 需要自己去实验
generator.saveAsImage(new File("D:\\1.png"));

// 直接生成byte[]
BufferedImage bufferedImage = generator.getBufferedImage();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
    ImageIO.write(bufferedImage, "jpg", outputStream);
    byte[] bytes = outputStream.toByteArray();
} catch (IOException e) {
    throw new RuntimeException("生成失败", e);
}
-------------------------

loadUrl(url)  (从url载入html)
loadHtml(html) (载入本地html)
saveAsImage(file) (以图片形式保存html)
saveAsHtmlWithMap(file, imageUrl) (创建一个HTML文件包含客户端image-map)
getLinks()(列出所有在HTML文档的链接和相应href、目标、头衔、位置和尺寸)
getBufferedImage() (获得awt,html缓冲后的图片)
getLinksMapMarkup(mapName) (HTML代码段里获得的客户端image-map <地图>产生的链接)
get/setOrientation(orientation) (get/set文本定位)
get/setSize(dimension)  (设置生成图片大小)

注意

这个组件依赖JEditorPane类,这个只支持HTML3.2标准,少量的css样式

根据javax.swing.text.html.CSS.java中的说明

font-family
font-style
font-size (supports relative units)
font-weight
font
color
background-color (with the exception of transparent)
background-image
background-repeat
background-position
background
text-decoration (with the exception of blink and overline)
vertical-align (only sup and super)
text-align (justify is treated as center)
margin-top
margin-right
margin-bottom
margin-left
margin
padding-top
padding-right
padding-bottom
padding-left
padding
border-top-style
border-right-style
border-bottom-style
border-left-style
border-style (only supports inset, outset and none)
border-top-color
border-right-color
border-bottom-color
border-left-color
border-color
list-style-image
list-style-type
list-style-position
posted @   Ranger-dev  阅读(775)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示