我正在通过servlet从我的Web应用程序生成一个用于门传递的pdf文件。我想在新窗口/选项卡中打开这个新生成的pdf,用户应该从servlet返回应用程序。如何在新窗口/标签中打开pdf?我从itext api生成pdf。我的servlet代码片段是:
response.setHeader("Expires", "0");
response.setHeader("Cache-Control","must-revalidate, post-check=0,precheck=0");
response.setHeader("Pragma", "public");
response.setContentType("application/pdf");
response.setContentLength(baos.size());
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
答案 0 :(得分:7)
如果您正在使用GET请求进行servlet调用
GET
将链接目标设置为target="_blank"
<a href="/url/to/servlet" target="_blank"/>
POST
<form method="post" action="url/to/servlet"
target="_blank">
所以浏览器会在新窗口/选项卡中发出新的GET / POST请求,然后将标题Content-disposition
设置为inline
以生成pdf内联而不是提示下载窗口
答案 1 :(得分:7)
/*create jsp page*/
<form action="OpenPdfDemo" method="post" target="_blank">
<input type="submit" value="post">
</form>
/* create servlet (servlet name = OpenPdfDemo)*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
ServletOutputStream outs = response.getOutputStream ();
//---------------------------------------------------------------
// Set the output data's mime type
//---------------------------------------------------------------
response.setContentType( "application/pdf" ); // MIME type for pdf doc
//---------------------------------------------------------------
// create an input stream from fileURL
//---------------------------------------------------------------
File file=new File("X://Books/struts book/sturts_Books/struts-tutorial.pdf");
//------------------------------------------------------------
// Content-disposition header - don't open in browser and
// set the "Save As..." filename.
// *There is reportedly a bug in IE4.0 which ignores this...
//------------------------------------------------------------
response.setHeader("Content-disposition","inline; filename=" +"Example.pdf" );
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
InputStream isr=new FileInputStream(file);
bis = new BufferedInputStream(isr);
bos = new BufferedOutputStream(outs);
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}
catch(Exception e)
{
System.out.println("Exception ----- Message ---"+e);
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}