java+phantomjs将网页生成图片

2019-12-05  本文已影响0人  至爱雅鸿_e631

前言

EChart图表插件很强大,这么好看的图表生成图片通过邮件发给各个负责人将是一个很好的体验,因此在各大网站一顿搜索,其中简单好用的就是phantomjs,特别好用

开干

准备条件

mac安装方法

##解压即用,你说简单不
tar xvf phantomjs-2.1.1-macosx.zip
##软连到bin目录下,目录换成自己的,方便使用phantomjs(当然也没咋用这个命令只检查了下版本)
ln -sf /Users/zhiaiyahong/development/phantomjs-2.1.1-macosx/bin/phantomjs /usr/local/bin/phantomjs
##检查是否成功
phantomjs --version

linux安装方法我是在本地下载好安装包上传到服务器的

##解压即用
tar xvf phantomjs-2.1.1-linux-x86_64.tar.bz2
##检查是否可用,进入bin目录
cd phantomjs-2.1.1-linux-x86_64/bin
##检查版本
./phantomjs --version

window安装方法,应该也挺简单的~ 应该就是一顿下一步

 <!--phantomjs -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.14.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.codeborne/phantomjsdriver -->
        <dependency>
            <groupId>com.codeborne</groupId>
            <artifactId>phantomjsdriver</artifactId>
            <version>1.4.4</version>
        </dependency>
搬砖

废话不多说直接上代码

package com.yhwch.fun.service;

import com.yhwch.fun.param.SaveHtmlParam;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HtmlToImageService {
    //phantomjs的并目录,绝对路径
    private static String PHANTOM_JS_BIN_PATH = "/Users/zhiaiyahong/development/phantomjs-2.1.1-macosx/bin/phantomjs";
    //图片保存路径
    private static String SAVE_PATH = "/Users/zhiaiyahong/development/";

    public static String saveHtml(SaveHtmlParam saveHtmlParam){
        try {
            //设置必要参数
            DesiredCapabilities dcaps = new DesiredCapabilities();
            //ssl证书支持
            dcaps.setCapability("acceptSslCerts", true);
            //截屏支持
            dcaps.setCapability("takesScreenshot", true);
            //css搜索支持
            dcaps.setCapability("cssSelectorsEnabled", true);
            //js支持
            dcaps.setJavascriptEnabled(true);
            //驱动支持(第二参数表明的是你的phantomjs引擎所在的路径)
            dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
                    PHANTOM_JS_BIN_PATH);
            //创建无界面浏览器对象
            PhantomJSDriver driver = new PhantomJSDriver(dcaps);

            //设置隐性等待(作用于全局)
            driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
            long start = System.currentTimeMillis();
            //打开页面
            driver.get(saveHtmlParam.getUrl());
            Thread.sleep(saveHtmlParam.getOpenWaitMillis());
            //页面过长执行滚动
            if(saveHtmlParam.getScrollScreen()){
                JavascriptExecutor js = driver;
                for (int i = 0; i < saveHtmlParam.getScrollTimes(); i++) {
                    js.executeScript("window.scrollBy(0,"+saveHtmlParam.getScrollStep()+")");
                    Thread.sleep(saveHtmlParam.getScrollWaitMillis());
                }
            }
            //指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
            File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            Thread.sleep(saveHtmlParam.getSaveWaitMillis());
            //利用FileUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象
            String fileName = UUID.randomUUID().toString()+".png";
            FileCopyUtils.copy(srcFile, new File(SAVE_PATH + fileName));
            log.info("图片生成完毕,耗时:{}ms",System.currentTimeMillis() - start);
            return fileName;
        }catch (Exception e){
            log.error("保存异常,e=",e);
            return null;
        }
    }
}

package com.yhwch.fun.param;

import lombok.Data;

@Data
public class SaveHtmlParam {
    /**
     * 目标html地址
     */
    private String url;
    /**
     * 页面渲染需要的时间
     */
    private Long openWaitMillis;

    /**
     * 保存文件需要的时间
     */
    private Long saveWaitMillis;
    /**
     * 是否滚动屏幕
     */
    private Boolean scrollScreen = false;
    /**
     * 滑动的步长
     */
    private Integer scrollStep = 1000;
    /**
     * 滑动次数 phantomjs截取最大的高度为32767px(int  32位的最大整数)
     * 因此在默认参数前提下最多滚33次
     */
    private Integer scrollTimes = 33;
    /**
     * 每次滑动等待的时长
     */
    private Long scrollWaitMillis = 1000L;

    public SaveHtmlParam(String url,Long openWaitMillis,Long saveWaitMillis){
        this.url = url;
        this.openWaitMillis = openWaitMillis;
        this.saveWaitMillis = saveWaitMillis;
    }
}

--测试类

import com.yhwch.fun.Bootstrap;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.Test;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Bootstrap.class, webEnvironment=RANDOM_PORT)
public class BaseTest {
@Test
public void test(){
HtmlToImageService.saveHtml(new SaveHtmlParam("http://localhost:1321/monitor/chart",1000L,1000L));
}
}

效果如下图


image.png

参考文章

java利用phantomjs进行截图实例教程

上一篇 下一篇

猜你喜欢

热点阅读