Hi I am go for the generate excel file form the array but I am not getting successes. I am work using node.js and I am use npm package for generate excel file but I am not getting any data in excel file. excel is generate but not getting any type of data in my file. so any one know where is my mistake then please let me know how can fix it.
This is my array and query =>
var XLSX = require('xlsx');
var Array = [];
Array.push({
username: 'Carakc',
fullName: 'Crack',
followingCount: 2655,
followerCount: 466,
biography: 'I am new man'
},
{
username: 'mahi',
fullName: 'Fit',
followingCount: 3011,
followerCount: 385,
biography: 'hello everyone!'
})
app.get(prefix + '/GetFollowersInExcel', function (req, res, next) {
var ws = XLSX.utils.json_to_sheet(Array);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Followres");
var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
res.end(wbout, 'binary');
}
});
}
});
})
This is my service code =>
GetFollowersInExcel: function (InstaId) {
return $http({
method: "GET",
url: ONURL + "GetFollowersInExcel",
responseType: "arraybuffer",
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}).then(function (data, status, xhr) {
debugger;
if (data.data.byteLength > 0) {
var file = new Blob([data.data], { type: 'application/binary' });
var fileURL = URL.createObjectURL(file);
$('#getexcel').show();
var link = document.createElement('a');
link.href = fileURL;
link.download = "myfile.xlsx";
link.click();
URL.revokeObjectURL(file);
}
}, function (error) {
return error;
})
},
using this wave I am getting like this data in excel =>
I want like this data in excel file =>
I've tried your first code and I've found no errors, the resulting xlsx is perfect.
Peheraps I've found the problem: var Array is declared outside the app.get callback... Are you sure that your var Array can be correctly reached by XLSX.utils.json_to_sheet? it's in the same scope? or it's declared somewhere inaccessible?
try to declare it inside the callback and probably all will work well, and, if this is the case, you can use a class or a method to retrieve the var from outside ("how" depends on your code)
P.s. change the name of the var, is not a good habit overwrite the Array object ;)
Related
The plan is to create a pdf file (that only consists of a single page) then the user chooses whether to download as PDF or image. I have already written the code for generating the PDF and it is working fine as of now. The problem now is how to convert this to image. Is it possible to convert files without installing stuff like Ghostscript etc?
I am a complete noob, advice is greatly appreciated. (Recommendations on which libraries to use would also be helpful)
Code for generating the PDF
import PDFDocument from "pdfkit";
static async medicalPrescription(req, res) {
// Some code for generating the PDF contents...
filename = encodeURIComponent(filename) + '.pdf'
res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"')
res.setHeader('Content-type', 'application/pdf')
const content = req.body.content
doc.y = 300
doc.text(content, 50, 50)
doc.pipe(res)
doc.end()
}
The client then receives the generated file and opens it in another tab.
React file that sends the request and opens the response
const handleSubmit = async (e) => {
// Some code for sending the pdf content from the user
fetch("http://localhost:5050/generate-rx", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: parsed
})
.then(async res => {
if (res.status === 200) {
const blob = await res.blob();
const file = new Blob(
[blob],
{type: 'application/pdf'}
);
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
})
}
You can use pdf2pic. It can convert pdf to image.
import { fromPath } from "pdf2pic";
const options = {
density: 100,
saveFilename: "untitled",
savePath: "./images",
format: "png",
width: 600,
height: 600
};
const storeAsImage = fromPath("/path/to/pdf/sample.pdf", options);
const pageToConvertAsImage = 1;
storeAsImage(pageToConvertAsImage).then((resolve) => {
console.log("Page 1 is now converted as image");
console.log(resolve); // send resolve to user
});
I am following the documentation in https://developers.virustotal.com/v3.0/reference#file trying to analyze files through VirusTotal API using the endpoint https://www.virustotal.com/api/v3/files but it keeps throwing the following error:
{"error": {
"message": "Received file with an empty filename. Please post with filename.",
"code": "BadRequestError"\n
}
}
The code I'm using is really simple, and I have change it adding more keys in the data object like: "name", filename", and so on but seems nothing is working:
class VirusTotal {
constructor(){
this.APIKEY = CONF.virus_apikey;
}
async checkFile(path){
let url = 'https://www.virustotal.com/api/v3/files';
let header = {'x-apikey': this.APIKEY};
let data = {file:path, name: path.split('/')[path.split('/').length -1], filename: 'asdasd'};
REQUEST(url, ['post'], data, (err, res, status, headers) => {
console.log(err, res, status, headers);
}, null, header);
}
}
Then I tried to do it through the GUI they have to test, but didn't work either, throwing the same error.
To upload a file to their API it reaquires a to read the file, pass it as a Buffer and stringify it.
I got the next solution:
async analyzeFile(path, fileType){
return new Promise((resolve, reject) => {
let file = require('fs').readFileSync(path);
const Buffer = require('buffer').Buffer;
if (typeof input=="string") file = Buffer.from(file, 'utf8')
if (Buffer.isBuffer(file)) file = file;
file = JSON.stringify(file);
const request = require('request');
request({
url: 'https://www.virustotal.com/api/v3/files',
method: 'POST',
headers: {'x-apikey': this.APIKEY},
formData: {file: {value: file, options: {filename: path.split('/')[path.split('/').length -1], filetype: fileType}}},
}, async (err, res) => {
!err ? resolve(res) : reject(err);
});
});
}
As well, per VirusTotal staff the GUI they has a bug, therefore it doesn't work.
This is a Meteor-app. I need to generate a docx-file and download it.
I am testing it by running: localhost:3000/download.
Word file is generated, but it is totally empty.
Why? I would appreciate any advice!
This is my server-side code:
const officegen = require('officegen');
const fs = require('fs');
Meteor.startup(() => {
WebApp.connectHandlers.use('/download', function(req, res, next) {
const filename = 'test.docx';
let docx = officegen('docx')
// Create a new paragraph:
let pObj = docx.createP()
pObj.addText('Simple')
pObj.addText(' with color', { color: '000088' })
pObj.addText(' and back color.', { color: '00ffff', back: '000088' })
pObj = docx.createP()
pObj.addText(' you can do ')
pObj.addText('more cool ', { highlight: true }) // Highlight!
pObj.addText('stuff!', { highlight: 'darkGreen' }) // Different highlight color.
docx.putPageBreak()
pObj = docx.createP()
let out = fs.createWriteStream(filename);
res.writeHead(200, {
'Content-Disposition': `attachment;filename=${filename}`,
'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
res.end(docx.generate(out));
});
});
The problem you are facing is that docx.generate(out) is an async function: when calling res.end(docx.generate(out)) you end the request right now while you start generating the docx in the file test.docx. Hence the doc does not exist yet.
You should modify your code to send over the file directly like this:
res.writeHead(200, {
'Content-Disposition': `attachment;filename=${filename}`,
'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
docx.generate(res)
If you still need the file on the server side you can use another approach waiting for the file being generated (see here)
I have an angular + node application that has the ability nto download excel files rendered using the exceljs package.
All the work (except for getting the data for the excel) is done throught the client side. The problem is that the browser couldn't handle such amount of data.
What I'm trying to do now is basically do all the work in the server and the client should get the data as buffer array [buffer] and save it.
This my code which worked: (below you can see the fixed version)
Component :
//The this.srv.getExcel() only return observable of data returned from the DB
this.srv.getExcel().subscribe(result =>
{
let workbook = new Workbook();
workbook.addWorksheet('sheet1');
result.forEach(dataItem => worksheet.addRow(Object.keys(dataItem).map(di => dataItem[di]))); //populating the excel
workbook.xlsx.writeBuffer().then((data) =>
{
const data: Blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
FileSaver.saveAs(data, 'excelFile.xlsx');
});
})
Now - Trying to convert it (SOLVED):
Component:
this.nodeSrv.getExcel(request, fileName).subscribe(result =>
{
const data: Blob = new Blob([request], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'});
FileSaver.saveAs(data, fileName + '.xlsx');
},
error => { debugger; this.loading = false; }
)
service with http to the end point on the server:
getExcel(request, fileName)
{
var path = reportsUrl.GetVotingBoxListForExcel;
const options = { withCredentials: true };
return this.http.post<any>(path, {request: request, reportName : fileName }, options);
}
This is the main change - most of te work is in the server - This is the nodeSrv:
router:
const express = require('express');
const router = express.Router();
router.use(req, res, next) =>
{
//The GetDataForExcel is the same as this.srv.getExcel() only return promise of data returned from the DB
return DB.GetDataForExcel(req.body.request).then((dataResult) => {
let reportTypeNameForExcel = req.body.reportName ? req.body.reportName : '';
return excel.createExcel(res, dataResult, reportTypeNameForExcel);
}).catch((err) => {
next({
details: err
})
});
})
module.exports = router;
This is the excel.createExcel, something is probably wrong here
createExcel : function(res, dataResult, reportTypeNameForExcel)
{
let workbook = new Workbook();
workbook.addWorksheet('sheet1');
dataResult.forEach(dataItem => worksheet.addRow(Object.keys(dataItem).map(di => dataItem[di]))); //populating the excel
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
workbook.xlsx.write(res).then(() =>
{
res.end();
})
}
The code above is already fixed - solved
I am working on a Meteor application.
Currently, I have a few PDFs on my server. To serve these already existing PDFs directly to the client, I do it this way and it works very well:
Router.route("/file/:fileName", function() {
var fileName = this.params.fileName;
// console.log(process.env.PWD);
var filePath = process.env.PWD + '/' + fileName;
var fs = Meteor.npmRequire('fs');
var data = fs.readFileSync(filePath);
this.response.writeHead(200, {
"Content-Type": "application/pdf",
"Content-Length": data.length
});
this.response.write(data);
this.response.end();
}, {
where: "server"
});
I save these PDFs to Mongo using CollectionFS (Later, I shall generate PDFs and save them. For now, I am just directly saving these already existing PDFs to Mongo as I first want to get the Mongo part to work.).
testCollection = new FS.Collection("testCollection", {
stores: [new FS.Store.GridFS("testCollection")]
});
testCollection.allow({
'insert': function () {
return true;
}
});
var file = new FS.File(process.env.PWD + '/PDFKitExampleServerSide.pdf');
file.encoding = 'binary';
file.name('myPDF.pdf');
var document = testCollection.insert(file);
console.log(document._id);
My question is, after I save these PDFs to Mongo using CollectionFS (like I do above), how do I retrieve and serve these PDFs?
Router.route("/database/:pdfId", function() {
//need help here
}, { where: "server"});
After a lot of searching and trying, I've finally gotten it to work.
Router.route("/database/:pdfId", function() {
var pdfId = this.params.pdfId;
var file = testCollection.findOne({_id: pdfId});
var readable = file.createReadStream("tmp");
var buffer = new Buffer(0);
readable.on("data", function(b) {
buffer = Buffer.concat([buffer, b]);
});
var response = this.response;
readable.on("end", function() {
response.writeHead(200, {
"Content-Type": "application/pdf",
"Content-Length": buffer.length
});
response.write(buffer);
response.end();
});
}, {
where: "server"
});
I know that this question is old, but I found an easier way to store and retrieve PDFs. Apparently if you store your PDFs in the database and they are smaller than 16MB (which is likely in this type of files) the performance is way slower than if you store the files in your server file system.
For doing that, you can use FS.Store.FileSystem instead of FS.Store.GridFS. The following code works for me:
// Client
var pdfStore = new FS.Store.FileSystem("uploadedFiles");
UploadedFiles = new FS.Collection("uploadedFiles", {
stores: [pdfStore],
filter: {
allow: {
extensions: ['pdf','doc','docx','xls','xlsx','ppt','pptx''jpg','png','jpeg']
}
}
});
// Server
var pdfStore = new FS.Store.FileSystem("uploadedFiles", {path: uploadFilesPath});
UploadedFiles = new FS.Collection("uploadedFiles", {
stores: [pdfStore],
filter: {
maxSize: 5242880, // 5MB in bytes
allow: {
extensions: ['pdf','doc','docx','xls','xlsx','ppt','pptx''jpg','png','jpeg']
},
deny: {
extensions: ['exe']
},
onInvalid: function (message) {
if (Meteor.isClient) {
alert(message);
} else {
console.log(message);
}
}
}
});
And then just use this little helper to retrieve the url to the file:
get_uploaded_link: function(id){
console.log(id);
var file = UploadedFiles.findOne({_id: id});
return file.url();}