I am unable to convert a PDF file to uint8, which I get as a response to an API request. When printing out the response in the console, it has this form:
%PDF-1.4
%����
1 0 obj
<</CreationDate(D:20231025135518+02'00')/Creator( ... >>
endobj
2 0 obj
...
I am trying to display the PDF I get as a response, in a new browser tab. The snippet of code I use to convert and display this response looks like this:
let response = await this.getDocument(id);
if(response.status === 200){
let responseText = await response.text();
let uint8Array = new Uint8Array(responseText.length);
for (let i = 0; i < responseText.length; i++) {
uint8Array[i] = responseText.charCodeAt(i);
}
var file = new Blob([uint8Array], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
When I run this code, a new browser tab opens, the pdf it displays is empty however. When running the same request with Postman, I am getting the same response, only that Postman is able to display the correct PDF instead of a blank one. Running console.log(responseText);
prints out the previously stated response, which is the same as the one I get in Postman.
At this point, I should add that this code is part of a Lightning Web Component, I am trying to develop on Salesforce, in case a valid answer does not work.
I have been trying to figure out how to solve this issue for a while, so any help or pointers are appreciated.
Try to get the response as ArrayBuffer instead of text
. Then, pass the arrayBuffer
to Uint8Array constructor.
const arrBuff = await response.arrayBuffer();
const uint8Array = new Uint8Array(arrBuff);
const file = new Blob([uint8Array], { type: 'application/pdf' });