A server response to an Axios request contains the content of a PDF as a binary string.
export const fetchPDFfile = async (id: string): Promise<string> => {
const { data } = await http.get<string>(`${baseUrl}/${id}.pdf`);
return data;
};
When viewed in Chrome devtools or logged in the console, the data appears as follows:
%PDF-1.4
%âãÏÓ
2 0 obj <</ColorSpa ......
..........
startxref
10991
%%EOF
- Is defining
string
as the expected type of response body from Axios correct, or should it be (cast to) Blob?
Now, I aim to download this as a PDF file on the client-side. Despite numerous attempts and unanswered questions, I have not been successful.
My current approach (in a React component) involves:
const data = await fetchPDFfile(props.id);
const blob = new Blob([data], { type: 'application/pdf' });
const href = window.URL.createObjectURL(blob);
const theLink = document.createElement('a');
theLink.href = href;
theLink.download = props.id + '.pdf';
document.body.appendChild(theLink);
theLink.click();
document.body.removeChild(theLink);
Downloading this results in a PDF file with 3 blank pages. The original document should be 3 pages long, but the pages are empty.
const href = window.URL.createObjectURL(data); // instead of blob
throws an error.
What is the correct way to convert and download this PDF file? Generally, is the above process necessary, or should I directly download it from the server (similar to what cordova-plugin-file-transfer does)?