根据url在线显示PDF

一个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查出来的东西没有数据时,会报错,目前还在研究中。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值