维基html转pdf或者html转image图片是一款C++编写的软件,基于QT Webkit rendering engine生成图片和pdf。
可以参考 https://wkhtmltopdf.org 查看更多的文档和资料,使用它我们需要下载和安装该软件到本地。
使用java调用,可参考如下调用:
/**
* 1.wkhtmltoimage http://xxx/xxx/index.html C:\Users\xuchang\Desktop\imgae\test2.jpg
*
* 2.wkhtmltopdf http://xxx/xxx/index.html C:\Users\xuchang\Desktop\imgae\test3.pdf
*
* 3.C:\Program" "Files" ("x86")"\wkhtmltopdf\wkhtmltoimage.exe --width 1024 --height 768 http://www.google.com/
* D:\example.jpg
*
* 4.wkhtmltopdf --page-width 50 http://xxx/xxx/index.html C:\Users\xuchang\Desktop\imgae\test7.pdf
*/
@Test
public void testGenerateImage() {
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Process process = Runtime
.getRuntime()
.exec(
"D:/wkhtmltopdf/bin/wkhtmltoimage.exe http://xxx/xxx/index.html C:/Users/xuchang/Desktop/imgae/test4.jpg");
Future<List<String>> inputStreamToByteArray = executor.submit(streamToByteArrayTask(process
.getInputStream()));
Future<List<String>> outputStreamToByteArray = executor.submit(streamToByteArrayTask(process
.getErrorStream()));
process.waitFor();
if (process.exitValue() != 0) {
System.out.println("getErrorStream:" + getFuture(outputStreamToByteArray));
System.out.println("getInputStream:" + getFuture(inputStreamToByteArray));
}
System.out.println("getErrorStream:" + getFuture(outputStreamToByteArray));
System.out.println("getInputStream:" + getFuture(inputStreamToByteArray));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
executor.shutdownNow();
}
}
/**
* @param input xx
* @return xx
*/
private Callable<List<String>> streamToByteArrayTask(final InputStream input) {
return new Callable<List<String>>() {
public List<String> call() throws Exception {
return IOUtils.readLines(input, "utf-8");
}
};
}
/**
* @param future xx
* @return xx
*/
private List<String> getFuture(Future<List<String>> future) {
try {
return future.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
throw new RuntimeException(e);
}
}