【问题标题】:Showing PDF bytestream in the response in a new browser window在新浏览器窗口的响应中显示 PDF 字节流
【发布时间】:2014-09-10 09:52:51
【问题描述】:

我正在尝试使用 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 文件,而是显示字节本身。

这是我得到的输出

如何在此处显示从字节流中提取的实际文件?

【问题讨论】:

  • 我正在发送 json 数据并将 pdf 作为流返回
  • win.document 是一个 HTML 文档。你写什么并不重要。

标签: javascript html spring-mvc pdf


【解决方案1】:

我根本无法让它工作。所以我想出了一个替代方案。在 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;
}

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 2015-05-02
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    相关资源
    最近更新 更多