在新的浏览器窗口中显示响应中的PDF字节流

时间:2014-09-10 09:52:52

标签: javascript html spring-mvc pdf

我正在尝试使用Javascript在新窗口中弹出PDF文件的字节流。

在后端我使用的是Spring Controller代码,如下所示

@RequestMapping(value = "/print", method = RequestMethod.POST, consumes="application/json")
public ModelAndView printCompareChart(@RequestBody ChartGenerationRequest request,
        HttpServletRequest httpRequest ) throws Exception {

   byte [] bytes =//bytestream of a pdf file
   ModelAndView mav = new ModelAndView();
   mav.addObject("byteArray", bytes);
   mav.setViewName("pdfByteArrayPrint");
   return mav;
 }

此post方法由JS的AJAX调用调用,如此

$.ajax({
    url: url,
    cache: false,
    type:'POST',
    data: JSON.stringify(data),
    contentType:"application/json; charset=UTF-8",
    success: function (responseData){
        var win=window.open('about:blank', target, windowProperties);
        with(win.document)
        {
          open();
          write(responseData);
          close();
        }
    }
});

从chrome开发人员工具中我可以看到响应数据以字节形式出现,但在新的浏览器窗口中,它不显示实际的pdf文件,而是显示字节本身。

这是我得到的输出

output window 如何从字节流中提取实际文件?

1 个答案:

答案 0 :(得分:0)

我根本无法解决这个问题。所以我想出了一个替代方案。从JS方面我创建了一个隐藏的表单并提交了数据,后端用pdf字节流回复,然后显示在新的浏览器窗口中。在这种情况下,我不得不牺牲自动json转换为java对象,并从传递的httpRequest中单独处理每个参数。

JS代码

openWithPost = function(url, title, data, target) {

  var form = document.createElement("form");
  form.action = url;
  form.method = "POST";
  form.target = target || "_self";
  if (data) {
    for ( var key in data) {
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = key;
        input.value = data[key];
        form.appendChild(input);
    }
  }
  form.style.display = 'none';
  document.body.appendChild(form);
  form.submit();
}

后端Spring代码

@RequestMapping(value = "/printCompareChart", method = RequestMethod.POST)
public ModelAndView printCompareChart(HttpServletRequest httpRequest)
{
   //get each parameter from httpRequest and handle it
   String fileName = httpRequest.getParameter("fileName");
   //logic to create the pdf file
   byte[] bytes = //get bytes of the pdf file
   ModelAndView mav = new ModelAndView();
   mav.addObject("byteArray", bytes);
   mav.setViewName("pdfByteArrayPrint");
   return mav;
}