html或其它文件转pdf弹出打开保存框
第一步:下载wkhtmktopdf软件,安装在指定的目录,如:C:\htmlToPdf\wkhtmltopdf,
第二步:把安装好的wkhtmltopdf文件目录加到环境变量Path路径中,
publicvoidconvertFile(){
HttpURLConnectioncon=null;
URLurl=null;
Processp=null;
Stringcmd="html2pdf";//安装文件目录名,此名是在linux下的,其它可以自己加目录
try{
Stringsessionid=Struts2Util.getRequest().getSession().getId();
System.out.println("sessionid=="+sessionid);
url=newURL(
"http://10.168.2.181:8080/scm/quote_extra!print.action");
con=(HttpURLConnection)url.openConnection();
con.setRequestProperty("Cookie","JSESSIONid="+sessionid);
con.connect();
intsize=0;
byte[]buf=newbyte[1024];
BufferedInputStreambis=newBufferedInputStream(con
.getInputStream());
StringBufferstrb=newStringBuffer();
while((size=bis.read(buf))!=-1){
strb.append(newString(buf,0,size));
}
FileWriterwriter=null;
Filefile=newFile("/tmp/quote_print.html");
writer=newFileWriter(file);
writer.write(strb.toString());
writer.flush();
writer.close();
ProcessBuilderpb=newProcessBuilder(cmd,"/tmp/quote_print.html",
"/tmp/quote_print.pdf");//使用插件进行转换
pb.redirectErrorStream(true);
p=pb.start();
InputStreamReaderir=newInputStreamReader(p.getInputStream());
LineNumberReaderinput=newLineNumberReader(ir);
Stringline;
while((line=input.readLine())!=null){
System.out.println(line);
}
//提示下载
HttpServletResponseresponse=Struts2Util.getResponse();
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("Content-Disposition","attachment;filename="
+"PrintQuote"+(newRandom()).nextInt()+".pdf");//PackingSlip是文件名
java.io.OutputStreamos=response.getOutputStream();
java.io.FileInputStreamfis=newjava.io.FileInputStream(
"/tmp/quote_print.pdf");
byte[]b=newbyte[1024];
inti=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(Exceptione){
e.printStackTrace();
thrownewRuntimeException(e);
}finally{
if(p!=null){
p.destroy();
}
}
}