Getting echarts pictures in java background

Getting echarts pictures in java background

Usage scenarios

In recent projects, you need to save the echarts line chart displayed in the page to word to generate a briefing

Using Selenium and ChromeDriver

Selenium

compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.7.1'

ChromeDriver

Chrome driver download link
ps: Please note that the downloaded version must correspond to the chrome version installed locally
Comparison table

I used: Google Chrome version 73.0.3683.103 (official version)
The downloaded chrome driver is 73.0.3683.68

After downloading, I put it under the path of D:\chromedriver\chromedriver.exe

Prepare an html

<html>
<meta charset="UTF-8">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<head>
    <script src="http://gssn.fw121.com/js/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/3.8.0/echarts.min.js"></script>
</head>
<body>
<!-- Because I need to generate two images, I define two echarts -->
<!-- by ECharts Prepare a DOM  -->
<div id="temEcharts" style="height:400px;width:550px"></div>
<div id="rhEcharts" style="height:400px;width:550px"></div>
</body>
<script>
    var temEcharts = null;
    var rhEcharts = null;
    $(function () {
        // Initialize the echarts instance based on the prepared dom
        temEcharts = echarts.init(document.getElementById('temEcharts'));
        rhEcharts = echarts.init(document.getElementById('rhEcharts'));
    });
    function showImg(data) {
//        var option = {
//            xAxis: {
//                type: 'category',
//                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
//            },
//            yAxis: {
//                type: 'value'
//            },
//            series: [{
//                data: [820, 932, 901, 934, 1290, 1330, 1320],
//                type: 'line'
//            }]
//        };
//        rhEcharts.setOption(option);
        rhEcharts.setOption(data);
    }

    function returnEchartImg(echartObj) {
        return echartObj.getDataURL();
    }


</script>
</html>


Background code

public class WebDriverUtil {


    private static BASE64Decoder decoder = new sun.misc.BASE64Decoder();



    public static void main(String []s){
        getImgByte("{     xAxis: {         type: 'category',         data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']     },     yAxis: {         type: 'value'     },     series: [{         data: [820, 932, 901, 934, 1290, 1330, 1320],         type: 'line'     }] }");
    }

    /**
     * Get picture byte
     */
    public static byte[] getImgByte(String option) {
        WebDriver driver = null;
        try {
            driver = getWebDriver();
            //Visit URL
            driver.get("F:\\ideaWorkspaseGit\\fw-wealth-api\\src\\main\\resources\\html\\zhixiantu.html");
            //Timeout for page load
            System.out.println(driver.getCurrentUrl());
            JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("showImg(" + option + ")");
            //Delay for 1 second and wait for the completion of line drawing
            Thread.sleep(1000);
            String imgTxt = js.executeScript("return returnEchartImg(rhEcharts)").toString().replace("data:image/png;base64,", "");
            System.out.println("----------------" + imgTxt);
            base64StringToImage(imgTxt);
            return decoder.decodeBuffer(imgTxt);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            driver.close();
            driver.quit();
        }
        return null;
    }


    /**
     * Initialize WebDriver
     *
     * @return
     */
    public static WebDriver getWebDriver() {
        // Set the path load driver of chrome driver
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver.exe");
        //Setting the headless mode of chrome
        ChromeOptions chromeOptions = new ChromeOptions();
        //Headless mode
        chromeOptions.setHeadless(true);
        //data in address:,
//        chromeOptions.addArguments("--user-data-dir=C:/Users/Administrator/AppData/Local/Google/Chrome/User Data/Default");
        //Chrome is under the control of automatic software. No prompt is displayed
        chromeOptions.addArguments("disable-infobars");
        //Start a chrome instance
        return new ChromeDriver(chromeOptions);
    }


    /**
     * Save pictures
     *
     * @param base64String
     */
    public static void base64StringToImage(String base64String) {
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            File file= new File("d://123345457.jpg");
            ImageIO.write(bi1, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Tags: Selenium Java Google JQuery

Posted on Thu, 28 Nov 2019 09:18:22 -0800 by kevinlcarlson