Convert Buffer to PDF - javascript

I am building a PDF using Puppeteer on the server and returning it as a Buffer to the client for download. I can't figure out why this conversion is not working for download. If I download it on the server side, everything works fine. Where am I going wrong?
onSuccess(data) {
const blob = new Blob([data as Buffer], { type: 'application/pdf' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'test.pdf'
link.click()
},

This always happens, I figure it out right after posting.
The answer is nuanced. I'm using React Query to get the data. The Buffer coming back from Node and Puppeteer looks like:
{ type: Buffer, data: [...] }
The data to convert is on the data property, not the Buffer itself. So the correct code looks like this:
onSuccess(data) {
const blob = new Blob([data.data as Buffer], { type: 'application/pdf' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'test.pdf'
link.click()
},
This felt hacky (and made TS upset) so I kept searching and decided to convert the PDF to base64 before returning to client and that seems be working as well. On the server that looks like:
const pdf = await page.pdf()
const base64 = pdf.toString('base64')
return `data:application/pdf;base64,${base64}`

Related

URL.createObjectURL() providing url that redirects to 404 in AWS production env

I have a django application deployed on AWS EBS. I have a function that takes a blob and create URL of it so that I can download the pdf file from the site. The function is working perfectly on localhost but in prod environment the created url from URL.createObjectURL() is redirecting to the error page or 404 page. Im using nginx as the reverse proxy. I have checked the blob is valid and the django function is generating the pdf layout correctly. Below is my js code to build the pdf download link
function showFile(blob){
var newBlob = new Blob([blob], {type: "application/pdf"})
if (!newBlob) {
console.error("Blob object is not valid");
return;
}
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
console.log(data)
var link = document.createElement('a');
link.href = data;
link.open="file.pdf";
link.download = 'Calculation.pdf';
link.click()
}
the console.log(data) is returning https://<mydomain>/d6527ea6-5c1d-457a-bfb2-2b6aff01ae31
Any idea on how I can make it work in my prod env?
Thank you
I tried to log the flow and everything is returning correctly. So I am not sure what is the issue

Upload picture to Digital Ocean Space using Expo

I'm trying to upload the image result from the takePictureAsync function to a Digital Ocean Space using Expo. Currently the upload process using signed PUT URL seems to work fine, but something is going wrong during the encoding process. Below I've included the relevant code:
const pictureResponse = await camera.current.takePictureAsync({ base64: true });
const spacesBase64 = `data:image/png;base64,${pictureResponse.base64}`;
const spacesBuffer = Buffer.from(spacesBase64, "base64");
const spacesBlob = new Blob([spacesBuffer]);
const spacesFile = new File([spacesBlob], "test.jpg", { type: "image/jpeg" });
fetch(`https://signedputurl.com`, { method: 'PUT', body: spacesFile });
When I take a picture it shows up on my Digital Ocean Space just fine. The file size also seems correct. When I try to preview the URL it doesn't render. I've tried removing the data:image/png;base64 prefix, but this doesn't fix the problem.
I've made the image result public and it can be viewed at https://disposable-dev.ams3.digitaloceanspaces.com/with_base64_prefix.jpg, I figured it might be helpfull.
I've figured out a solution! Instead of parsing the base64 results back into a blob. I can just use a fetch request to get the blob from cache.
const pictureResponse = await camera.current.takePictureAsync();
const spacesRespond = await fetch(pictureResponse.uri);
const spacesBlob = await spacesRespond.blob();
fetch(`https://signedputurl.com`, { method: 'PUT', body: spacesBlob });

Not able to upload Video File using blobUrl

I'm trying to upload video using blobUrl, but it is not getting uploaded properly and always giving file size 64 bytes. Following is the code I have written.
onFilesSelected(evt) {
const file = evt.target.files[0];
const videoBlobUrl = URL.createObjectURL(file);
fileObject = new File([videoBlobUrl], file.name, { type: file.type });
const formData = new FormData();
formData.append('file', fileObject);
formData.append('type', 'video');
// Send `formData` to API
}
Can anyone please help me, what I'm doing wrong.
P.S.: I am not using FileReader API, because for large files it's too slow to show the preview.

pdf file corrupt after downlod in react js

Unable to request service with blob content-type by REST API (GET), the file goes corrupted, below is a snippet that I used to get get the file.
PDF File is retrive from docware
while checking the downloaded pdf file size is less than the original file from the server and it was corrected.
handleDownload(url,fileName){
var element = document.createElement("a");
var file = new Blob([url], { type: "application/pdf", });
element.href = URL.createObjectURL(file);
element.download = fileName;
element.click();
}

Problem opening downloaded zip file using javascript

I am trying to open a downloaded a zip file sent to me against a GET request. I am using axios for my api requests.
PROBLEM
File is downloaded. But I am not able to extract or open it. Empty archive issue.
What I am using?
This is my response handler:
const data = response.data
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", `report.zip`);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
The API works fine. Tested with Postman. Able to download and work with files within that zip.
The above code works fine for csv file type.
I suspect that Blob thing. Please share what could be the problem.
I'm not 100% sure, but maybe you're just missing the type for the blob. This is the function I'm using to download files with Ajax. There's also a special path for Internet Explorer/Edge, because it will block the synthetic link click.
const downloadFile = (data, filename, type = "application/zip) => {
const blob = new Blob([data], { type })
if(navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob,filename)
} else {
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
So you can use it in your code:
const data = response.data
downloadFile(data, "report.zip")

Categories

Resources