一个servlet用来实现PDF online preview的效果,在此记录一下:
public void download(HttpServletRequest request, HttpServletResponse response) throws FileGenerationException{
response.reset();
response.setContentType("application/pdf");
response.setCharacterEncoding("UTF8");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Content-Disposition", "inline;filename=pdfTemp.pdf");
HttpClient httpClient = new DefaultHttpClient();
try {
InputStream is = null;
try {
String pdfUrl = (String)WebUtils.getSessionAttribute(request, "pdfUrl");
//下面这个方法对于很多url是支持的,但是当时项目中用到的url不支持,于是就没有采用这种方法
/*HttpGet getMethod = new HttpGet(pdfUrl);
HttpResponse response1 = httpClient.execute(getMethod);
if(response1.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
HttpEntity en = response1.getEntity();
byte[] bytes = EntityUtils.toByteArray(en);
is = new ByteArrayInputStream(bytes);
}else{
throw new FileGenerationException("Server error");
}
IOUtils.copy(is, response.getOutputStream());*/
// 这是现在采用的方法
URL u = new URL(pdfUrl);
HttpURLConnection httpUrl = null;
httpUrl = (HttpURLConnection) u.openConnection();
is = new DataInputStream(httpUrl.getInputStream());
//DataOutputStream out = new DataOutputStream(response.getOutputStream());
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[4096];
int count = 0;
while ((count = is.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
} finally {
if (is != null) {
is.close();
}
response.getOutputStream().flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
httpClient.getConnectionManager().shutdown();
}
}
不足之处在于,当url查出来的东西没有数据时,会报错,目前还在研究中。