使用cssbox将html文件转为图片文件


在我的另一篇博客 使用freemarker动态填充html并可转为图片中,大家已经了解到如何使用freemarker动态填充html文件了,那么如何将html文件转为图片文件呢?

1. 引入依赖

<dependency>
    <groupId>net.sf.cssbox</groupId>
    <artifactId>cssbox</artifactId>
    <version>4.14</version>
</dependency>

2. 编写Util类

public class Html2ImageUtil {

	public static void transferHtml2Image(String htmlFilePath, String imageFilePath, Integer width, Integer height) {
		ImageRenderer render = new ImageRenderer();
		render.setWindowSize(new Dimension(width, height), false);
		String url = new File(htmlFilePath).toURI().toString();
		try {
			FileOutputStream out = new FileOutputStream(imageFilePath);
			render.renderURL(url, out, ImageRenderer.Type.PNG);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

3. 调用Util

Html2ImageUtil.transferHtml2Image("result.html", "result.png", WIDTH_IMAGE, HEIGHT_IMAGE);

然后就可在项目根目录下找到生成的名为"result.png"的图片文件啦。

4. 存在的问题

对于外部引用的js不支持;虽然存在不完美的地方,但仍然不失为一个好用的html转图片的工具哦~

5. 改进

如果大家觉得效果不够好,可以尝试使用cssbox的5.0.0版本,详见我的另一篇博客:使用5.0.0版本的cssbox将html文件转为图片文件,并解决字体显示问题

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kuo-Teng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值