0
我使用spring boot,jquery和itext。在Firefox的標籤中顯示pdf內容
當用戶點擊一個按鈕,一個pdf文件是genereated。
@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');
});
}