(一)使用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);
    });
}

整個過程比較簡單,但是從技術選型,到開發,調試也歷時一個星期。

最后附上筆者生成的圖片

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM