angular download pdf file error - javascript

In my angular app I get pdf byte and show the file using blob
This is my code
siteService.downloadPdf().then(function (response) {
var file = new Blob([response], { type: 'application/pdf' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file);
}
else {
var fileURL = URL.createObjectURL(file);
window.location.href = fileURL;
}
});
When I try to download the file I got an error that the file does not saved
This error is when I save the file as is (without the .pdf) and also after adding the .pdf

Related

Upload PDF file as BLOB and downloading as PDF again

I'm am trying to upload a pdf file, convert it to a BLOB and download again as a pdf file. At the moment I get no errors but when I download the file I get a blank pdf with what looks like a corrupted file name.
I am saving the BLOB in the pdfFile vairable.
<input type="file"
#change="onNewFileUpload($event)">
async onNewFileUpload($event) {
const file = $event.target['files'][0];
const fileReader = new FileReader();
const self = this;
fileReader.onload = function() {
pdfFile = new Blob([fileReader.result], { type: "application/pdf" })
}
fileReader.readAsText(file);
},
<button
#click="downloadPdfFile()"
class="btn btn-success">Download pdfFile</button>
downloadBOBSCertificate() {
const link = document.createElement('a');
// create a blobURI pointing to our Blob
// link.href = pdfFile;
link.href = URL.createObjectURL(pdfFile);
link.download = 'test.pdf';
// some browser needs the anchor to be in the doc
document.body.append(link);
link.click();
link.remove();
// in case the Blob uses a lot of memory
setTimeout(() => URL.revokeObjectURL(link.href), 7000);
}

I am getting error when i am trying to convert HTML to PDF, How can I resolve this?

I convert html data from response to pdf but got the error...my code is
this.httpClient.post("/getreport/1", obj, { responseType: 'arraybuffer' }).subscribe((data) => {
var dd=new Uint8Array(data)
var file = new Blob([dd], { type: 'application/pdf' });
filename = this.report.key + ".pdf";
let $link = document.createElement("a");
let url = URL.createObjectURL(file);
$link.setAttribute("target", "_blank");
$link.setAttribute("href", url);
$link.setAttribute("download", filename);
$link.style.visibility = "hidden";
document.body.appendChild($link);
$link.click();
});
ERROR: FAILED TO LOAD PDF

doesn't able to download image in react using blob

I have a QR code that is coming from the database in the base64 format. I have to download this image on a button click. I use this function to download the image on button click. the function runs successfully and I able to download the image, but when I try to open the image, an error message comes in 'Photos', 'Paint' type application says the file is not supported. I use same code for download an CSV data and it is working perfectly fine.
What is the error in this code?
export const downloadCSV=(data, filename,image)=>
{
var downloadLink;
if(image !== null && image === true)
{
var dataType = 'image/png';
}
else{
var dataType = 'application/vnd.ms-excel';
}
var filename = filename;
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', data], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
downloadLink.href = 'data:' + dataType + ', ' + data;
downloadLink.download = filename;
downloadLink.click();
}
}

Download file using java script and spring boot

This is my javascript code :
$('#downloadTraining').on('click', function () {
$.get(restbase() + "/download-training/" + $('[name=trainingId]').val()).done(function(data) {
}).fail(function(data) {
errorAlert();
}).always(function(data) {
});
});
And this is my spring boot controller method :
#GetMapping("/r/download-training/{trainingId}")
public ResponseEntity<InputStreamResource> download(#PathVariable("trainingId") Integer trainingId) throws FileNotFoundException, JRException, IOException{
File file = jasperReportService.createTrainingReport(trainingId);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
// Content-Disposition
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
// Content-Type
.contentType(MediaType.parseMediaType("application/octet-stream"))
// Contet-Length
.contentLength(file.length()) //
.body(resource);
}
Calling get method from javascript is working. Getting file is working. But it doesn't download file. Is there anything i need to add to javascript or error is in Java ?
Response and request headers : http://prntscr.com/lh01zx
I have a solution but I don't know if this is what you are expecting. Firstly I have never heard of sprint-boot before so sorry about that. But when it comes to downloading files with JavaScript I always use this method. This method downloads files with a blob and directly from the browser.
code:
//saving and downloading a file with a js blob;
function downloadFile(data, filename, type) {
var file = new Blob([data], {type: type});
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, filename); //IE 10+
} else {
var a = document.createElement("a");
var url = window.URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
I got this code from this question:
JavaScript: Create and save file

Getting corrupted word document when using FileSaver and Blob in angularjs

I am using angular-file saver service https://github.com/alferov/angular-file-saver for downloading files. Download is good but when try to open word document I am getting file is corrupted and word cannot open it and if put my api directly in browser file is good when I open it so I suppose blob is doing something for this issue... For .txt files I am not getting corrupted it is good only for .docx and for .jpeg or .png. Below is my short code for downloading files.
function downloadDocument(fileId, fileName, documentExt) {
var deferred = $q.defer();
var id = encodeURIComponent(fileId);
Restangular.one('download?fileId=' + id).get().then(function(data) {
var file = new Blob([data]);
if (documentExt && documentExt !== 'undefined') {
FileSaver.saveAs(file, fileName + '.' + documentExt);
}
else {
FileSaver.saveAs(file, fileName);
}
});
return deferred.promise;
}
you can use give below code to save your file--
function downloadDocument(fileId, fileName, documentExt) {
var deferred = $q.defer();
var id = encodeURIComponent(fileId);
Restangular.one('download?fileId=' + id).get().then(function(data) {
// try to use data.data or data in blob object
var file = new Blob([data.data], {
type: 'application/octet-binary'
});
var fileUrl = URL.createObjectURL(file);
// for IE 10+
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file, fileName+'.'+documentExt);
} else {
var element = document.createElement('a');
element.href = fileUrl;
element.setAttribute('download', fileName+'.'+documentExt);
element.setAttribute('target', '_blank');
document.body.appendChild(element);
element.click();
}
});
return deferred.promise;
}

Categories

Resources