在firefox的选项卡中显示pdf内容

时间:2017-08-18 01:17:13

标签: javascript spring firefox

我使用spring boot,jquery和itext。

当用户点击某个按钮时,会生成一个pdf文件。

@GetMapping(value = "/members/{memberId}/contract/{contractId}/generalcontracts", produces = "application/pdf")
public ResponseEntity<byte[]> getMemberContract(@PathVariable("memberId") Long memberId, @PathVariable("contractId") Long contractId) throws IOException {
    byte[] content = reportService.generateMemberContractReport(contractId);
    return prepareReport(content);
}

private ResponseEntity<byte[]> prepareReport(byte[] content) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    String filename = "report.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
    return response;
}

打开选项卡并显示文件。

该代码适用于chrome但不适用于firefox。 使用firefox,它就像打开和关闭标签一样。

<button id="memberPrintReport" type="button"  class="btn btn-primary">Imprimer</button>

$("#memberPrintReport").on('click', function (e) {


 tryit(getHostName() + "/members/" + memberId + "/contract/" + contractId + "/generalcontracts");
}    

function tryit(urlServer) {
    var win = window.open('_blank');
    downloadFile(urlServer, function (blob) {
        var url = URL.createObjectURL(blob);
        win.location = url;
    });
}

function downloadFile(url, success) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.setRequestHeader("Authorization", "Basic " + $.cookie('authorization'));
    xhr.responseType = "blob";
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (success)
                success(xhr.response);
        }
    };
    xhr.send(null);
}

function tryit(urlServer) {
  downloadFile(urlServer, function (blob) {
    var url = URL.createObjectURL(blob);
     window.open(url, '_blank');

  });
}

1 个答案:

答案 0 :(得分:1)

尝试更新此行

headers.setContentDispositionFormData(filename, filename);

到这个

headers.setContentDispositionFormData("inline", filename);

如果这不起作用,那么试试这个:

headers.add("content-disposition", "inline;filename=" + filename)