(一)使用phantomjs将动态HTML页面生成图片

因为工作需要,笔者需要将一个动态的HTML5页面生成图片,并将图片发送给用户。

其中难点在于怎样将动态H5生成图片

笔者翻阅资料后,决定使用phantomjs这个插件,关于这个插件的安装,非常简单,笔者不再赘述。

安装好插件后就是怎样使用这个插件了。

下面附上笔者的调用

private void exePhantomjs(String url,String filename){
        String BLANK = " ";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(
                    phantomjs + BLANK //你的phantomjs.exe路径
                    + calendarjs + BLANK //就是上文中那段javascript脚本的存放路径
                    + url + BLANK //你的目标url地址
                    + filePath+filename+".jpg");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         logger.info(phantomjs + BLANK+calendarjs + BLANK+url + BLANK+filePath+filename+".jpg");
         InputStream inputStream = process.getInputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
         String tmp = "";
         try {
            while ((tmp = reader.readLine()) != null) {
                 if (process != null) {
                     process.destroy();
                     process = null;
                 }
             }
            inputStream.close();
            reader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         System.out.println("渲染成功...");
    }
    

 这里相当是JAVA直接调用第三方插件。需要传入四个参数

1,phantomjs的路径

2,执行脚本

3,动态H5的地址,可以使用百度地址进行测试,笔者在开发时使用了自己后台的H5页面

4,图片生成路径

接下来附上笔者的脚本

var page = require('webpage').create(), system = require('system'), address, output, size;

if (system.args.length < 3 || system.args.length > 5) {
    phantom.exit(1);
} else {
    address = system.args[1];
    output = system.args[2];
    //定义宽高
    page.viewportSize = {
        width : 1242,
        height : 10000
    };
    page.open(address, function(status) {
        
        var bb = page.evaluate(function() {
            return document.getElementsByTagName('html')[0].getBoundingClientRect();            
        });
        var cc = page.evaluate(function() {
             return document.documentElement;
            
        });
        page.clipRect = {
            top : bb.top,
            left : bb.left,
            width : bb.width,
            height : cc.scrollHeight
        };
        window.setTimeout(function() {
            page.render(output);
            page.close();
            console.log('success...');
            
            //for (var item in cc){
            //    if('scrollHeight'==item){
            //        console.log(item,cc[item])
            //    }
            //}
            console.log('height',cc.scrollHeight)
            
            phantom.exit(1);
        }, 1000);
    });
}

整个过程比较简单,但是从技术选型,到开发,调试也历时一个星期。

最后附上笔者生成的图片

猜你喜欢

转载自www.cnblogs.com/weiziyu/p/12016083.html