html或其它文件转pdf弹出打开保存框

第一步:下载wkhtmktopdf软件,安装在指定的目录,如:C:\htmlToPdf\wkhtmltopdf,
第二步:把安装好的wkhtmltopdf文件目录加到环境变量Path路径中,


public void convertFile(){
HttpURLConnection con = null;
URL url = null;
Process p = null;
String cmd = "html2pdf";//安装文件目录名,此名是在linux下的,其它可以自己加目录
try {
String sessionid = Struts2Util.getRequest().getSession().getId();
System.out.println("sessionid==" + sessionid);
url = new URL(
"  http://10.168.2.181:8080/scm/quote_extra!print.action");
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", "JSESSIONID=" + sessionid);
con.connect();
int size = 0;
byte[] buf = new byte[1024];
BufferedInputStream bis = new BufferedInputStream(con
.getInputStream());
StringBuffer strb = new StringBuffer();
while ((size = bis.read(buf)) != -1) {
strb.append(new String(buf, 0, size));
}
FileWriter writer = null;
File file = new File("/tmp/quote_print.html");
writer = new FileWriter(file);
writer.write(strb.toString());
writer.flush();
writer.close();
ProcessBuilder pb = new ProcessBuilder(cmd, "/tmp/quote_print.html",
"/tmp/quote_print.pdf");//使用插件进行转换
pb.redirectErrorStream(true);
p = pb.start();
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
// 提示下载
HttpServletResponse response = Struts2Util.getResponse();
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("Content-Disposition", "attachment; filename="
+ "PrintQuote" + (new Random()).nextInt() + ".pdf");// PackingSlip是文件名
java.io.OutputStream os = response.getOutputStream();
java.io.FileInputStream fis = new java.io.FileInputStream(
"/tmp/quote_print.pdf");
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) > 0) {
os.write(b, 0, i);
}
fis.close();
os.flush();
response.flushBuffer();
os.close();
bis.close();
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);

}finally{
if(p!=null){
p.destroy();
}
}
}

你可能感兴趣的:(html,C++,c,linux,OS)