java把html转成图片的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/superit401/article/details/82629524
  1. 代码

1.1 html模版

static String HtmlTemplateStr =

"<style type=\"text/css\">"+  

"body {background-color: yellow}"+

"h1 {background-color: #00ff00}"+

"h2 {background-color: transparent}"+

"p {background-color: rgb(250,0,255)}"+

"p.no2 {background-color: gray; padding: 20px;}"+

"</style>"+



"<img src=\"http://p1.img.cctvpic.com/photoAlbum/page/performance/img/2018/8/21/1534782617583_424.jpg\" width=\"660\" height=\"380\" alt=\"cctv.com图片\" />"+



"<h1>我是h1标题</h1>"+



"<div id=\"\" class=\"\">"+

"<img src=\"http://115.182.9.166/cportal/photoAlbum/page/performance/img/2017/5/26/1495792113125_553.jpg\" width=\"480\" height=\"300\" alt=\"cportal图片\" />"+

"<h1>这是标题 1</h1>"+

"<h2>这是标题 2</h2>"+

"<p>这是段落</p>"+

"<p class=\"no2\">这个段落设置了内边距。</p>"+

"<input type=\"button\" value=\"1\" onclick=\"点我\" />"+

"<input type=\"text\" id=\"ww\" name=\"\" value=\"hahahah\"/>"+

"</div>"+



"<table border=\"1\" background=\"http://www.w3school.com.cn/i/eg_bg_06.gif\">"+

"<tr>"+

  "<th>Month</th>"+

  "<th>Savings</th>"+

"</tr>"+

"<tr>"+

  "<td>January</td>"+

  "<td><p>这是第一行</p></td>"+

"</tr>"+

"<tr>"+

  "<td><img src=\"http://p1.img.cctvpic.com/photoAlbum/page/performance/img/2018/8/21/1534782617583_424.jpg\" width=\"660\" height=\"380\" alt=\"cctv.com图片\" /></td>"+

  "<td><h1>这是第二行</h1></td>"+

"</tr>"+

"</table>"+



"<p>有序列表:</p>"+

"<ol>"+

"<li>打开冰箱门</li>"+

"<li>把大象放进去</li>"+

"<li>关上冰箱门</li>"+

"</ol>"+



"<p>无序列表:</p>"+

"<ul>"+

"<li>雪碧</li>"+

"<li>可乐</li>"+

"<li>凉茶</li>"+

"</ul>";

1.2 引用的转换工具jar包

import gui.ava.html.image.generator.HtmlImageGenerator;

 

1.3 主要转换代码逻辑

import gui.ava.html.image.generator.HtmlImageGenerator;  


public class Html2ImageTest {

static String htmlTemplate = HtmlTemplate.HtmlTemplateStr;

    public static void main(String[] args) {  

        HtmlImageGenerator imageGenerator = new HtmlImageGenerator();  

        //加载html模版
        imageGenerator.loadHtml(htmlTemplate);

        //把html写入到图片
        imageGenerator.saveAsImage("hello-world.png");  
       }  
}

 

  1. 转换耗时

简单的html页面0.3-0.5秒之间;

稍复杂点的页面在0.9秒甚至更多一点。

  1. 转换结果图片

 

使用cctv.com和cportal的图片可正常显示,使用百度图库、一些素材库网如17sucai的图片不可正常显示。

  1. 结果评估
  1. 大部分常用的Html元素如h1、p、div、img、table、li、lu等可带样式转换成功,目前常用的input标签转换不成功,在生成的图片中不显示。图片大小显示正常。
  2. 转换耗时在0.3-1秒之间,可接受,不影响用户体验。

猜你喜欢

转载自blog.csdn.net/superit401/article/details/82629524
今日推荐