PDF Blob - всплывающее окно, не отображающее содержимое
Я работаю над этой проблемой за последние несколько дней. Если вам не удастся показать поток на теге <embed src>
, я просто попытался отобразить его в новом окне.
В новом окне отображаются только файлы только < → " →
Любая идея, почему содержимое pdf не отображается?
CODE:
$http.post('/fetchBlobURL',{myParams}).success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
Ответы
Ответ 1
Вам нужно установить responseType
в arraybuffer
, если вы хотите создать blob
из ваших данных ответа:
$http.post('/fetchBlobURL',{myParams}, {responseType: 'arraybuffer'})
.success(function (data) {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
Дополнительная информация: Sending_and_Receiving_Binary_Data
Ответ 2
Если вы установите { responseType: 'blob' }
, вам не нужно создавать Blob
самостоятельно. Вы можете просто создать URL-адрес на основе содержимого ответа:
$http({
url: "...",
method: "POST",
responseType: "blob"
}).then(function(response) {
var fileURL = URL.createObjectURL(response.data);
window.open(fileURL);
});
Ответ 3
Я использую AngularJS v1.3.4
HTML:
<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>
JS-контроллер:
'use strict';
angular.module('xxxxxxxxApp')
.controller('MathController', function ($scope, MathServicePDF) {
$scope.downloadPdf = function () {
var fileName = "test.pdf";
var a = document.createElement("a");
document.body.appendChild(a);
MathServicePDF.downloadPdf().then(function (result) {
var file = new Blob([result.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
});
};
});
Услуги JS:
angular.module('xxxxxxxxApp')
.factory('MathServicePDF', function ($http) {
return {
downloadPdf: function () {
return $http.get('api/downloadPDF', { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
};
});
Java REST Web Services - Spring MVC:
@RequestMapping(value = "/downloadPDF", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<byte[]> getPDF() {
FileInputStream fileStream;
try {
fileStream = new FileInputStream(new File("C:\\xxxxx\\xxxxxx\\test.pdf"));
byte[] contents = IOUtils.toByteArray(fileStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "test.pdf";
headers.setContentDispositionFormData(filename, filename);
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
} catch (FileNotFoundException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
return null;
}
Ответ 4
Я боролся в течение нескольких дней, и решение, которое сработало для меня, дано ниже. Я должен был заставить window.print()
для PDF в новом окне работать.
var xhr = new XMLHttpRequest();
xhr.open('GET', pdfUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this['status'] == 200) {
var blob = new Blob([this['response']], {type: 'application/pdf'});
var url = URL.createObjectURL(blob);
var printWindow = window.open(url, '', 'width=800,height=500');
printWindow.print()
}
};
xhr.send();
Некоторые заметки о загрузке PDF & печать в новом окне.
- Загрузка pdf в новом окне через iframe будет работать, но печать не будет работать, если url является внешним URL.
- Всплывающие окна браузера должны быть разрешены, тогда только они будут работать.
- Если вы попытаетесь загрузить iframe из внешнего URL и попробовать
window.print()
, вы получите пустой отпечаток или элементы, исключающие iframe
. Но вы можете запустить печать вручную, что сработает.
Ответ 5
проблема в том, что он не конвертируется в правильный формат. Используйте функцию "printPreview (binaryPDFData)", чтобы получить диалоговое окно предварительного просмотра двоичных данных PDF.
Вы можете прокомментировать часть скрипта, если не хотите открывать диалог печати.
printPreview = (data, type = 'application/pdf') => {
let blob = null;
blob = this.b64toBlob(data, type);
const blobURL = URL.createObjectURL(blob);
const theWindow = window.open(blobURL);
const theDoc = theWindow.document;
const theScript = document.createElement('script');
function injectThis() {
window.print();
}
theScript.innerHTML = 'window.onload = ${injectThis.toString()};';
theDoc.body.appendChild(theScript);
};
b64toBlob = (content, contentType) => {
contentType = contentType || '';
const sliceSize = 512;
// method which converts base64 to binary
const byteCharacters = window.atob(content);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {
type: contentType
}); // statement which creates the blob
return blob;
};
Ответ 6
В итоге я просто скачал свой pdf, используя приведенный ниже код
function downloadPdfDocument(fileName){
var req = new XMLHttpRequest();
req.open("POST", "/pdf/" + fileName, true);
req.responseType = "blob";
fileName += "_" + new Date() + ".pdf";
req.onload = function (event) {
var blob = req.response;
//for IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
};
req.send();
}