convert bytearray into pdf javascript - javascript

i'm trying to download a pdf report (using jasperReports) directly from browser...
my JS code is above:
if (generateReport) {
Loader.get(`${window.location.origin}/api/${Version.TRIP}/expenses/report-analytics?${getUrlParamsForReport(entity)}`).then(response => {
const file = new Blob([response.data], { type: 'application/pdf' });
const fileURL = URL.createObjectURL(file);
window.open(fileURL, "EPrescription");
}).catch((error) => {
SnackbarController.add({
description: error.message,
duration: 3000,
});
Promise.reject(onError(error));
});
}
in my java code, the response is:
return bos.toByteArray();
pdf opens but has no content, no header, nothing!!
help?

Related

How to open PDF in a new tab from Cloud without downloading it in local machine

I am trying to open a PDF file in a new tab and want to read file without downloading it in local machine.
I tried this function, but it is not loading my pdf and giving error can not load pdf
function readFileInNewTab (fileId) {
let url = BASE_URL + "api/CMS/Documents/Download/" + fileId;
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/pdf', ...authHeader(url) },
credentials: 'include',
responseType: "blob", // important
};
inProgress = true;
return fetch (url, requestOptions).then(handleResponse)
.then((response)=> {
const file = new Blob([response], { type: "application/pdf" });
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
debugger
const pdfWindow = window.open();
pdfWindow.location.href = fileURL;
})
.catch((error) => {
console.log(error);
});
} ```

File format not supported but when decoding it with base64 it works fine

Hello i'm having issue with uploading image to the cloud (Backblaze B2).
The problem is, when I use the example Thunder client to upload the file everything works fine and file is shown.
Now my problem is that when I upload with JS I don't know why it is corrupted or bugged.
Like when I upload an image and download it, Windows File Manager says : file format not supported.
I decoded the file with base64 img decoder and it works fine and image is shown.
const submitForm = () => {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
// binary data
let imagedata = reader.result.slice(reader.result.indexOf(',') + 1)
console.log(imagedata);
console.log(sha1(imagedata));
const proxyurl = "https://cors-anywhere.herokuapp.com/";
let datadf = fetch(proxyurl + 'url', {
method: 'POST',
headers: {
"Accept": "*/*",
"User-Agent": "Thunder Client (https://www.thunderclient.io)",
"X-Bz-File-Name": file.name,
"X-Bz-Content-Sha1": "do_not_verify",
"Authorization": "auth",
"Content-Type": "b2/x-auto",
},
body: imagedata,
})
.then((response) => {
return response.json();
})
.catch((err) => {
return {
status: 'fail',
message: 'API CALL ERROR',
error: err.message
};
});
datadf.then(res => console.log(res))
};
reader.onerror = function(e) {
// error occurred
console.log('Error : ' + e.type);
};
.readAsDataURL() converts the file it reads into Base64, so it can be represented as a URL you can put into a browser. A very long URL, but still a URL.
If you store a Base 64 representation of an image into a file on your machine, then try to read it with an image-display program, the operation will fail: "This doesn't look like a .jpg, .png, or .gif" so I don't know what to do with it." That's what your Windows file manager error message means.
If you want the file's contents raw rather than Base64 encoded, you'll need to use .readAsArrayBuffer().

Getting PDF from Json API response

I have a problem with the PDF file I get from the API in response to a Json GET request.
It does get a good string in Json, however, which makes the PDF file that appears corrupted. I tried to convert the response to a string but it didn't do anything.
Here is my code:
getPDF() {
axios
.get(apiurl + "api/Dok", { params: { }, headers: { } })
.then(response => {
const res = response.data.fileData;
const pdfcode = res.toString();
this.convertPDF(pdfcode)
}
)
.catch(error => {
alert('error')
});
}
convertPDF(value) {
const file = new Blob(
[value],
{type: 'application/pdf'});
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
So if i'm import the pdf file from local and add it to this function istead of url in console i'm getting long string response
JVBERi0xLjUNCjQgMCBvYmoNCjw8L1R5cGUgL1BhZ2UvUGFyZW50IDMgMCBSL0NvbnRlbnRzIDUgMCBSL01lZGlhQ...
and PDF works, but when get it from URL i'm getting :
{"fileData":"JVBERi0xLjUNCjQgMCBvYmoNCjw8L1R5cGUgL1BhZ2UvUGFyZW50...
I checked it in notepad, the first answer and the content of "" are identical
any ideas what i can do?

How to convert blob to xlsx or csv?

The frontend of the application having a file download option (which can be in the following format: xlsx, csv, dat).
For that, I use fileSaver.js
Everything works fine for the format .dat/.csv but for the .xlsx it does not work the files are corrupted.
I tested the conversion with the following formats :
utf8
base64
binary
Here's how I do :
// /* BACK */ //
// data is
fs.readFile(filePath, (err, data) {...})
// the api give this answer the important part is "filename" & "data"
{"status":"ok","context":"writing the intermediate file","target":"/temp/","fileName":"name.xlsx","data":{"type":"Buffer","data":[72,82,65,67,67,69,83,83,32,10]}}
// /* FRONT */ //
let json = JSON.stringify(data)
let buffer = Buffer.from(JSON.parse(json).data)
let read = buffer.toString('utf8')
let blob = new Blob([read])
FileSaver.saveAs(blob, fileName)
Ok for anybody who pass in this topic, my solution :
(keep in mind the real better solution for dl a file : send file in api response with header 'Content-disposition' or use express for that like this)
The back (Node) work like this :
fs.readFile(filePath, (err, data) => {
if (err) {
console.log(`-------- oups error - read --------`)
console.log(err)
res.send({ status: `erreur`, context: `read the source file`, id: err.errno, code: err.code, message: err.message.replace(/\\/g, '/') })
} else {
res.send({ status: `ok`, context: `send data file`, target: target, fileName: fileName, data: data })
}
})
Here :
target is the path for the front with the name of the file and his
extension (/path/name.ext)
fileName is juste the name and the extension (name.ext)
data is the data send by the readFile ({"type":"Buffer","data":[72,82,65,67,67,69,83,83,32,10]})
The front (React) work like this :
fetch(targetUrl)
.then(res => res.json())
.then(res => {
if (res.status !== `ok`) {
this.setState({
errorDlFile: true,
errorDlFile_context: res.context,
errorDlFile_id: res.id,
errorDlFile_code: res.code,
errorDlFile_message: res.message
})
} else {
const target = res.target
const fileName = res.fileName
const data = res.data
const splitName = res.fileName.split('.')
const format = splitName[splitName.length-1]
// file saver blob solution
let json = JSON.stringify(data)
let buffer = Buffer.from(JSON.parse(json).data)
let readUTF8 = buffer.toString('utf8')
let blob = ''
if (format === 'xlsx') {
blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
} else if (format === 'csv') {
blob = new Blob([readUTF8], { type: 'application/vnd.ms-excel' })
} else {
blob = new Blob([readUTF8])
}
FileSaver.saveAs(blob, fileName)
}
})
#Hadock
if you want to download file with .csv extension then you need to pass the type of file like
let blob = new Blob([csv], { type: 'application/vnd.ms-excel' });
instead of
let blob = new Blob([read])
and don't forgot to send filename with extension (test.csv).
For excel file I used different plugin exceljs demo.
you can't save json data directly to .xlsx file, you can convert json data to excel format using library like 'sheetjs' (https://sheetjs.com/)
var ws_name = filename;//"SheetJS";
var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), filename + ".xlsx")

how to download an PDF from byteArraay in angular 6?

I am currently working in angular 6. i have to download pdf file from bytearray.
when i tried to download an pdf file. it downloads but when i open it. it shows error. please help me with it.
In the download.component.ts i am getting response as two values. first pdfname, second pdfbytearray. i am getting those values from component response.
sample response:
{
pdfName: "test.pdf",
pdfByteArray: "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9Qcm9kdWNlcij"
}
download.service.ts:
generatePdf(id) {
const httpOptions = {
'responseType': 'arraybuffer' as 'json'
};
return this.http.post<any>(URL.BASE_URL + 'application/generate?id='+ id,
{ httpOptions },
);
}
download.component.ts:
import { saveAs } from 'file-saver/FileSaver';
generatePdf() {
this.downloadApiService.generatePdf('4')
.subscribe( pdf => {
console.log('pdf response: ', pdf);
var mediaType = 'application/pdf';
var blob = new Blob([pdf.pdfByteArray], {type: mediaType});
let fileName = pdf.pdfName;
saveAs(blob, fileName);
}, err => {
console.log('Pdf generated err: ', JSON.stringify(err));
});
}

Categories