Despite the vast amount of research done on Stack Overflow regarding PDF downloading from a web service, none of the solutions provided have been successful in my case. This is a final attempt to seek help and possibly find answers. The scenario involves making a GET request to an API in order to retrieve a dynamically generated PDF file. Initially, we tried receiving the data as a byte[]
, but now we are opting for returning a stream containing the content. Here is the snippet from the web service controller:
var result = await resp.Content.ReadAsAsync<byte[]>();
var response = request.CreateResponse(HttpStatusCode.OK);
var dataStream = new MemoryStream(result);
response.Content = new StreamContent(dataStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "idcard.pdf";
var fileStream = new FileStream(@"c:\temp\temp.pdf", FileMode.Create);
fileStream.Write(result, 0, result.Length);
fileStream.Close();
return response;
The temporary save to the FileStream was just a test to ensure the data can be saved successfully to a file, which worked without any issues. However, saving it silently may not be user-friendly. It would be preferable if the PDF could either open in the browser or prompt for download through the browser.
Reviewing my Angular code reveals the following implementation:
.factory('memberIdCard', ['$http', function($http) {
var get = function() {
return $http({
method: 'GET',
url: '/Member/IdCard',
headers: {
accept: 'application/octet-stream'
},
responseType: 'arraybuffer',
transformResponse: function(data) {
var pdf;
console.log('data: ', data);
if (data) {
pdf = new Blob([data], {
type: 'application/pdf'
});
console.log('pdf: ', pdf);
}
return pdf;
}
})
}
return {
get: get
}
}]);
Attempts using both $http
and $resource
resulted in failure. Moving on to how this is handled in the controller:
$scope.printIdCard = function() {
memberIdCard.get().then(function(data) {
var pdf = data.data;
FileSaver.saveAs(pdf, 'idcard.pdf');
var pdfUrl = window.URL.createObjectURL(pdf);
$scope.pdfView = $sce.trustAsResourceUrl(pdfUrl);
window.open($scope.pdfView);
});
Note: The FileSaver
utility is sourced from angular-file-saver.
Following these steps results in a new window opening, but an error message stating "Failed to load PDF Document" appears. Attempts to open the document in Adobe Acrobat lead to another error mentioning compatibility issues or possible file damage due to decoding problems.
Any assistance offered would be highly appreciated. Despite implementing suggestions from various Stack Overflow threads, there might be something vital that I'm overlooking.
Thank you!