I´m trying to decode a Base64 String to a PDF. But the generated File is broken and I cant open it with Adobe Reader. What am I doing wrong?
This is my Code from server Side:
let data = req.body;
const base64String = data.pdf;
const pdfBuffer = Buffer.from(base64String, 'base64');
fs.writeFile('output.pdf', pdfBuffer,{encoding:"binary"}, err => {
if(err){
console.log(err)
}else{
console.log("PDF CREATED")
}
})
This is my Code from Client Side:
let pdf;
const createPDF = () => {
const report = new JsPDF('portrait','pt','a4');
report.html(document.querySelector(['.input_container'],[imageURL])).then(() => {
pdf = report.output('datauristring');
});
}
const data = {
pdf,
}
My Goal is when I manage to convert the base64 to PDF, to send this PDF as a Attachment with nodemailer.
Related
I'm trying to modify a pdf file that I get from the request then saving it in my server, I achieved to save it first as I received it from the request body and then modifying it, and once more saving it again with the modified version, but I was looking for another approach to modify it in the fly directly after receiving it from the request body then saving it only once in the server. I need to add a logo to the uploaded file, thanks in advance
This is my code
'''
const mongoose = require("mongoose");
const path = require("path");
const ErrorResponse = require("../utils/errorResponse");
const fs = require("fs");
// Form submition with photo
exports.uploadPdf = (req, folderPath, next) => {
if (!req.files) {
console.log("No file");
return next(new ErrorResponse("Please Upload a file", 400));
}
const file = req.files.pdf;
const extention = file.name.split(".").at(-1);
if (extention !== "pdf") {
console.log("It's not a valid PDF file");
return next(new ErrorResponse("Please Upload an pdf file", 400));
}
//Check image size
if (file.size > process.env.MAX_FILE_UPLOAD) {
return next(
new ErrorResponse(
`Please Upload an PDF file less than ${process.env.MAX_PDF_FILE_UPLOAD}`,
400
)
);
}
//Create custom filename
let id;
if (!req.params.id) {
id = mongoose.Types.ObjectId();
} else {
id = req.params.id;
}
file.name = `document_${id}${path.parse(file.name).ext}`;
var dir = `${process.env.FILE_UPLOAD_PATH}/${folderPath}`;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
file.mv(
`${process.env.FILE_UPLOAD_PATH}/${folderPath}/${file.name}`,
async (err) => {
if (err) {
console.log(err);
return next(new ErrorResponse(`Problem with file upload`, 500));
}
}
);
req.body = {
_id: id,
...req.body,
pdf: file.name,
};
};
'''
When I make the request with Postman or Thunder Client I can save the file, but when I try to do it from the browser I can't save it and the size is even larger than the original.
router.get('/files/download/:id', async (req, res) => {
try {
const { id } = req.params;
const file = await FileArea.findById(id);
if (!file) {
return res.status(404).send('File not found');
}
if (fs.existsSync (file.path)) {
const fileContents = fs.readFileSync(file.path); // read the file from the uploads folder with the path of the file in the database
const readStream = new stream.PassThrough(); // create a stream to read the file
readStream.end(fileContents); // end the stream
res.set('Content-disposition', 'attachment; filename=' + file.name); // set the name of the file to download with the name of the file in the database
res.set('Content-Type', file.type);
const fileToSend = readStream.pipe(res); // pipe the stream to the response
return fileToSend;
} else {
return res.status(404).send('File not found');
}
} catch (error) {
return res.status(500).send('Internal server error');
}
});
With this code from the frontend I try to put what is sent to a blob, which size is larger than the original file.
Example: The original file is 421KB and the Blob is 800KB
async downloadFiles(id: string) {
try {
const { data } = await downloadFile(id);
const blob = new Blob([data], { type: data.type });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', data.name);
document.body.appendChild(link);
link.click();
link.remove();
This is my code to get a dicom image from Google Cloud. It works well, but the image is lossy.
router.get("/dicomWebRetrieveInstance/dcmfile", async (req, res, next) => {
const writeFile = util.promisify(fs.writeFile);
emphasized textconst fileName = 'rendered_image.jpeg';
const cloudRegion = "us";
const projectId = "neurocaredicom";
const datasetId = "System_1";
const dicomStoreId = "Site_1A";
const studyUid = "1.2.276.0.7230010.3.1.2.296485376.1.1521713579.1849134";
const seriesUid = "1.2.276.0.7230010.3.1.3.2`enter code here`96485376.1.1521713580.1849651";
const instanceUid = "1.2.276.0.7230010.3.1.4.296485376.1.1521713580.1849652";
const parent = `projects/${projectId}/locations/${cloudRegion}/datasets/${datasetId}/dicomStores/${dicomStoreId}`;
const dicomWebPath = `studies/${studyUid}/series/${seriesUid}/instances/${instanceUid}/rendered`;
const request = {parent, dicomWebPath};
const rendered =
await healthcare.projects.locations.datasets.dicomStores.studies.series.instances.retrieveRendered(
request,
{
headers: "application/octet-stream; transfer-syntax=* ",
responseType: 'arraybuffer',
}
);
const fileBytes = Buffer.from(rendered.data);
await writeFile(fileName, fileBytes);
var options = {
root: path.join(__dirname),
};
// read binary data
var bitmap = fs.readFileSync(fileName);
// convert binary data to base64 encoded string
res.status(200).sendFile(fileName, options, function (err) {
if (err) {
next(err);
} else {
console.log(
`Retrieved rendered image and saved to ${fileName} in current directory`
);
}
});
});
Any solution to that problem would be appreciated, so anyone can help.
I am trying to save an excel file that I get from a post as base64, this conversion is done in my view, once I convert it, I try to save it with the xlsx library, this file is saving fine but when opening the file, it does not contain nothing. Can someone help me, in knowing what I am doing wrong?
my following code is:
private async getCurp(req: Request, res: Response) {
var datos = [];
let arrayusers = {};
const {
curp
} = req.body;
const newCurp = new CurpModel({
curp
});
const path = "C:\\Miroute"
var bufferFile = Buffer.from(curp, "base64");
const data = XLSX.read(bufferFile, { type: 'buffer' })
XLSX.writeFile(data, "excel.xls");
try {
return Ok<CurpType>(res, newCurp);
}
catch (error) {
console.log(error);
return ServerError(res);
}
In my component I convert my excel file to base64 in this way, iam using react
handleFileChange = e => {
let idCardBase64 = '';
this.getBase64(e.target.files[0], (result) => {
idCardBase64 = result;
console.log(idCardBase64)
this.setState({
file: idCardBase64,
})
});
}
getBase64(file, cb) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
cb(reader.result)
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
Please can someone help me?
My solution: I had not realized that my input parameter had a different name so it was undefined, the code looked like this:
private async getCurp(req: Request, res:Response){
var datos = [];
let arrayusers = {};
const {
file
} = req.body;
const newCurp = new CurpModel({
file
});
const bufferExcel = Buffer.from(newCurp.file.toString().replace("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64", ""),'base64');
const workbook = XLSX.read(bufferExcel, { type: 'buffer' });
const sheetNamesList = workbook.SheetNames;
// parse excel data to json
const excelData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNamesList[0]]);
console.log(excelData);
try{
return Ok<CurpType>(res, newCurp);
}
catch(error){
console.log(error);
return ServerError(res);
}
}
I'm using koajs as a framework for nodejs. I try to create csv data and response it to client but not working
let fields = ['code', 'status'];
let p = new Promise((resolve, reject) => {
json2csv({data: data, fields: fields }, (err, response) => {
if (err) {
reject(err);
} else {
resolve(response);
}
});
});
return p.then(data => {
let fileName = 'promotioncode-' + moment().unix();
ctx.response.attachment(fileName + '.csv');
ctx.response.type = 'application/ms-excel';
ctx.body = data;
})
The response is plan text data instead of attachment file
Here is response headers
Here is response body
If you would like to send a downloadable file attached to the body you need to create a read stream of the file.
const fs = require('fs');
ctx.set('Content-disposition', `attachment; filename=${result}`);
ctx.statusCode = 200;
ctx.body = fs.createReadStream(result);
Note: in result you have the file path
This worked for me:
ctx.set('Content-disposition', `attachment; filename=${fileName}.csv`);
ctx.statusCode = 200;
ctx.body = data;