1.上次写到根据url转为html文件
url转为html文件链接: 跳转链接.
2.此次把html转为pdf或者image的补上
本次采用wkhtmltopdf工具
下载链接: 点击下载.
当然如果部署到linux上面,自行下载对应版本,安装过程自行查看安装。
3 代码
/**
* html转pdf
* @param pdfToolPath wkhtmltopdf工具的执行路径,转成pdf就wkhtmltopdf,转成图片就wkhtmltoimage
* @param srcPath html路径,可以是硬盘上的路径,也可以是网络路径
* @param destPath pdf保存路径 (注意,必须与所转换的后缀对应,pdf后缀.pdf 图片可以.png .jpg等)
* @return 转换成功返回true
*/
public static boolean convert(String pdfToolPath, String srcPath, String destPath) {
File file = new File(destPath);
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
StringBuilder cmd = new StringBuilder();
cmd.append(pdfToolPath);
cmd.append(" ");
cmd.append(srcPath);
cmd.append(" ");
cmd.append(destPath);
boolean result = true;
try {
Process proc = Runtime.getRuntime().exec(cmd.toString());
HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
error.start();
output.start();
proc.waitFor();
} catch (Exception e) {
result = false;
e.printStackTrace();
}
return result;
}
public class HtmlToPdfInterceptor extends Thread {
private InputStream is;
public HtmlToPdfInterceptor(InputStream is) {
this.is = is;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line.toString()); // 输出内容
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样就会在指定位置生成对应的文件。批量的话可以按照时间生成对应的文件名,后续可以压缩成zip,方便下载。后续会写压缩成zip和下载。