下载一个资源包 phantomjs-2.1.1-windows引入一下
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by admin on 2019/2/15.
*/
@Service("HtmltoPicture")
public class HtmltoPicture {
private static String tempPath =System.getProperty("user.dir")+"\\chador-web\\src\\main\\webapp\\img";// 图片保存目录
private static String BLANK = " ";
// 下面内容可以在配置文件中配置
private static String binPath = "C:\\Users\\admin\\Desktop\\phantomjs-2.1.1-windows\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe";// 插件引入地址
private static String jsPath = "C:\\Users\\admin\\Desktop\\phantomjs-2.1.1-windows\\phantomjs-2.1.1-windows\\examples\\rasterize.js";// js引入地址
// 执行cmd命令
public static String cmd(String imgagePath, String url) {
return binPath + BLANK + jsPath + BLANK + url + BLANK + imgagePath;
}
//关闭命令
public static void close(Process process, BufferedReader bufferedReader) throws IOException {
if (bufferedReader != null) {
bufferedReader.close();
}
if (process != null) {
process.destroy();
process = null;
}
}
/**
* @param url
* @throws IOException
*/
public static void printUrlScreen2jpg(String url) throws IOException, InterruptedException {
String imgagePath = tempPath+"\\quanwang"+".png";//图片路径
//Java中使用Runtime和Process类运行外部程序
Process process = Runtime.getRuntime().exec(cmd(imgagePath,url));
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String tmp = "";
while ((tmp = reader.readLine()) != null) {
close(process,reader);
}
System.out.println("success");
}
public static void main(String[] args) throws IOException {
try {
String url = "";
HtmltoPicture.printUrlScreen2jpg(url);
}catch (Exception e){
}
}
}