I've written my code so far and can get a list of all the records to show up on a webpage, however I need to be able to get it as a CSV (comma separated values) file.
Right now the page shows a list like follows:
Name Address Description
Bob 1 street Journalist
Bill 2 street Fireman
etc...
Anyway I can have meteor create a CSV file for download, instead of it showing up as a webpage with all the HTML markup?
Based on How to serve a file using iron router or meteor itself?
HTML:
<template name="blah">
Download the CSV
</template>
JS:
// An example collection
var DummyData = new Mongo.Collection("dummyData");
// create some sample data
if (Meteor.isServer) {
Meteor.startup(function() {
var dummyDataCursor = DummyData.find();
if (dummyDataCursor.count() === 0) {
for(var i=1; i<=100; i++) {
DummyData.insert({Name: "Name" + i,Address: "Address" + i, Description:"Description" + i});
}
}
});
}
Router.route('/csv', {
where: 'server',
action: function () {
var filename = 'meteor_dummydata.csv';
var fileData = "";
var headers = {
'Content-type': 'text/csv',
'Content-Disposition': "attachment; filename=" + filename
};
var records = DummyData.find();
// build a CSV string. Oversimplified. You'd have to escape quotes and commas.
records.forEach(function(rec) {
fileData += rec.Name + "," + rec.Address + "," + rec.Description + "\r\n";
});
this.response.writeHead(200, headers);
return this.response.end(fileData);
}
});
Related
I need to extract 1st page of an uploaded PDF file(in SharePoint Online) & save it as a separate PDF file using JavaScript.
After some searching I found this. But I'm not able to understand how it works.
Please help.
As requested in the comment in a previous answer I am posting sample code to just get the first page in its original format, so not as a bitmap.
This uses a third party REST service that can PDF Convert, Merge, Split, Watermark, Secure and OCR files. As it is REST based, it supports loads of languages, JavaScript being one of them.
What follows is a self-contained HTML page that does not require any additional server side logic on your part. It allows a PDF file to be uploaded, splits up the PDF into individual pages and discards them all except for the first one. There are other ways to achieve the same using this service, but this is the easiest one that came to mind.
You need to create an account to get the API key, which you then need to insert in the code.
Quite a bit of the code below deals with the UI and pushing the generated PDF to the browser. Naturally you can shorten it significantly by taking all that code out.
<!DOCTYPE html>
<html>
<head>
<title>Muhimbi API - Split action</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
// ** Specify the API key associated with your subscription.
var api_key = '';
// ** For IE compatibility*
// ** IE does not support 'readAsBinaryString' function for the FileReader object. Create a substitute function using 'readAsArrayBuffer' function.
if (FileReader.prototype.readAsBinaryString === undefined) {
FileReader.prototype.readAsBinaryString = function (file_content) {
var binary_string = "";
var thiswindow = this;
var reader = new FileReader();
reader.onload = function (e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary_string += String.fromCharCode(bytes[i]);
}
thiswindow.content = binary_string;
$(thiswindow).trigger('onload');
}
reader.readAsArrayBuffer(file_content);
}
}
// ** For IE compatibility*
// ** Create a Blob object from the base64 encoded string.
function CreateBlob(base64string)
{
var file_bytes = atob(base64string);
var byte_numbers = new Array(file_bytes.length);
for (var i = 0; i < file_bytes.length; i++) {
byte_numbers[i] = file_bytes.charCodeAt(i);
}
var byte_array = new Uint8Array(byte_numbers);
var file_blob = new Blob([byte_array], {type: "application/pdf"});
return file_blob;
}
// ** Execute code when DOM is loaded in the browser.
$(document).ready(function ()
{
//** Make sure an api key has been entered.
if(api_key=='')
{
alert('Please update the sample code and enter the API Key that came with your subscription.');
}
// ** Attach a click event to the Convert button.
$('#btnConvert').click(function ()
{
// ** Proceed only when API Key is provided.
if(api_key=='')
return;
try
{
// ** Get the file object from the File control.
var source_file = document.getElementById('file_to_split').files[0];
//** Was a file uploaded?
if (source_file)
{
// ** Get the file name from the uploaded file.
var source_file_name = source_file.name;
var reader = new FileReader();
//** Read the file into base64 encoded string using FileReader object.
reader.onload = function(reader_event)
{
var binary_string;
if (!reader_event) {
// ** For IE.
binary_string = reader.content;
}
else {
// ** For other browsers.
binary_string = reader_event.target.result;
}
// ** Convert binary to base64 encoded string.
var source_file_content = btoa(binary_string);
if(source_file_content)
{
// ** We need to fill out the data for the conversion operation
var input_data = "{";
input_data += '"use_async_pattern": false';
input_data += ', "fail_on_error": false';
input_data += ', "split_parameter": 1';
input_data += ', "file_split_type": "ByNumberOfPages"';
input_data += ', "source_file_name": "' + source_file_name + '"'; // ** Always pass the name of the input file with the correct file extension.
input_data += ', "source_file_content": "' + source_file_content + '"'; // ** Pass the content of the uploaded file, making sure it is base64 encoded.
input_data += '}',
// ** Allow cross domain request
jQuery.support.cors = true;
// ** Make API Call.
$.ajax(
{
type: 'POST',
// ** Set the request header with API key and content type
beforeSend: function(request)
{
request.setRequestHeader("Content-Type", 'application/json');
request.setRequestHeader("api_key", api_key);
},
url: 'https://api.muhimbi.com/api/v1/operations/split_pdf',
data: input_data,
dataType: 'json',
// ** Carry out the conversion
success: function (data)
{
var result_code = "";
var result_details = "";
var processed_file_contents = "";
var base_file_name = "";
// ** Read response values.
$.each(data, function (key, value)
{
if (key == 'result_code')
{
result_code = value;
}
else if (key == 'result_details')
{
result_details = value;
}
else if (key == 'processed_file_contents')
{
processed_file_contents = value;
}
else if (key == 'base_file_name')
{
base_file_name = value;
}
});
// ** Show result code and details.
$("#spnResultCode").text(result_code);
$("#spnResultDetails").text(result_details);
if(result_code=="Success")
{
// ** Get first item in the array. This is the first page in the PDF
var processed_file_content = processed_file_contents[0];
// ** Convert to Blob.
var file_blob = CreateBlob(processed_file_content)
// ** Prompt user to save or open the converted file
if (window.navigator.msSaveBlob) {
// ** For IE.
window.navigator.msSaveOrOpenBlob(file_blob, base_file_name + "." + output_format);
}
else {
// ** For other browsers.
// ** Create temporary hyperlink to download content.
var download_link = window.document.createElement("a");
download_link.href = window.URL.createObjectURL(file_blob, { type: "application/octet-stream" });
download_link.download = base_file_name + ".pdf";
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
}
}
},
error: function (msg, url, line)
{
console.log('error msg = ' + msg + ', url = ' + url + ', line = ' + line);
// ** Show the error
$("#spnResultCode").text("API call error.");
$("#spnResultDetails").text('error msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
}
else
{
// ** Show the error
$("#spnResultCode").text("File read error.");
$("#spnResultDetails").text('Could not read file.');
}
};
reader.readAsBinaryString(source_file);
}
else
{
alert('Select file to convert.');
}
}
catch(err)
{
console.log(err.message);
// ** Show exception
$("#spnResultCode").text("Exception occurred.");
$("#spnResultDetails").text(err.message);
}
});
});
</script>
</head>
<body>
<div>
<form id="convert_form">
Select file: <input type="file" id="file_to_split" />
<br /><br />
<button id="btnConvert" type="button">Split PDF</button>
<br /><br />
Result_Code: <span id="spnResultCode"></span>
<br />
Result_Details: <span id="spnResultDetails"></span>
</form>
</div>
</body>
</html>
Big fat disclaimer, I worked on this service, so consider me biased. Having said that, it works well and could potentially solve your problem.
Finally found a solution.
First converting the uploaded PDF to image using PDF.JS, done some customization in the sample code.
Then saved the 1st page image as PDF using jsPDF.
The customized download code,
$("#download-image").on('click', function() {
var imgData = __CANVAS.toDataURL();
var doc = new jsPDF();
doc.addImage(imgData, 0, 0, 210, 300);
doc.save('page1.pdf');
});
I need to change the permission of every uploaded file. But when I try to add this code,
printPermissionIdForEmail(email) {
var request = gapi.client.drive.permissions.getIdForEmail({
'email': email,
});
request.execute(function(resp) {
return ('ID: ' + resp.id);
});
}
I got an error of getIdForEmail is not a function.
gapi.client.init, gapi.auth2.getAuthInstance(),
are working. But why gapi.client.drive.permissions.getIdForEmail is not working? There is something I need to do? in Google Developers Page? in my Code?
getIdForEmail is a method only available in Google Drive v2.
With V3 you are going to have to go after it in another manner.
Do a files.list with the q parameter. In the q parameter supply the user whos permissions you wish to change. You can see here how to use search This would find all the files where someuser is the owner.
'someuser#gmail.com' in owners
Then you will get a list of file resources you can then check the permissions on each file using permissions.list and use that to change the ones you need.
I am not a JavaScript developer but I found this in the documentation it shows how to use search to list files.
/**
* Print files.
*/
function listFiles() {
gapi.client.drive.files.list({
'q': "'someuser#gmail.com' in owners",
'fields': "*"
}).then(function(response) {
appendPre('Files:');
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendPre(file.name + ' (' + file.id + ')');
}
} else {
appendPre('No files found.');
}
});
}
Update:
I just spotted this. About.get Gets information about the user, the user's Drive, and system capabilities
{
"user": {
"kind": "drive#user",
"displayName": "Linda Lawton",
"photoLink": "xxxx",
"me": true,
"permissionId": "060305882255734372",
"emailAddress": "xxxx#gmail.com"
}
}
Could that be the same permissionId you were looking for?
The method I use is based on the OAuth2 library published on script.google.com. This is written for Google Apps Script with domain-wide delegation. The key here is building a valid url and option for UrlFetchApp.fetch(url, options), then parsing the result to find the ID number.
function getIdForEmailv3(userEmail) {
var service = getService(userEmail);
if (service.hasAccess()) {
Logger.log('getIdForEmailv3(%s) has access', userEmail);
var url = 'https://www.googleapis.com/drive/v3/about' + '?fields=user/permissionId'
var options = {
'method': 'get',
'contentType': 'application/json',
'headers': { Authorization: 'Bearer ' + service.getAccessToken() },
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
var resultString = JSON.stringify(response.getContentText());
var regex = new RegExp(/\d+/g);
var id = regex.exec(resultString)[0];
Logger.log('getIdForEmailv3 returned %s for %s', id, userEmail);
return id
} else {
Logger.log('getIdForEmailv3 getLastError: %s', service.getLastError());
Logger.log('getIdForEmailv3 returned %s for %s', 0, userEmail);
return 0;
}
}
Regex idea from: Easiest way to get file ID from URL on Google Apps Script
Fields format from comment on solution: How to add 'field' property to a Google Drive API v3 call in JavaScript?
I need to search for a folder in Google Drive, through a html page with javascript.
I have a javascript function that works:
function listFiles() {
var request = gapi.client.drive.files.list({
q: " mimeType = 'application/vnd.google-apps.folder' and name='SearchFolder' ",
pageSize: 10,
fields: "nextPageToken, files(id, name)"
});
request.execute(function (resp) {
console.log('Files:');
var files = resp.files;
if (files && files.length > 0) {
var file = files[0];
console.log(file.name + ' (' + file.id + ')');
} else {
console.log('No files found.');
}
});
Instead of that string at the q parameter, i tried to use something like this:
var folderSearch= 'TypeNameHere';
var string =JSON.stringify('mimeType = '+"'"+'application/vnd.google-apps.folder'+ "'"+' and name='+"'"+folderSearch+ "'" );
var request = gapi.client.drive.files.list({
q: string,
pageSize: 10,
fields: "nextPageToken, files(id, name)" });
But it doesn't work. How can I pass a variable in the request?
You had the right idea - just don't use JSON.stringify. That's for serialising (converting) an object to a string, but it's already a string.
Change the string to this...
var string = " mimeType = 'application/vnd.google-apps.folder' and name='" + folderSearch + "' ";
I want to develop an app for Pebble. This app is going to tell you how long it takes from one place you set in options to another one taking in account traffic jams and stuff.
To achieve this I need to make a page that will return JSON. Pebble retrieves information using code like that:
var cityName = 'London';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName;
ajax(
{
url: URL,
type: 'json'
},
function(data) {
// Success!
console.log('Successfully fetched weather data!');
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
I created a small page with a js script that gets needed information from Yandex API:
var route;
ymaps.ready(init);
var myMap;
function init(){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var time = 0;
var home = getParameterByName("h");
var work = getParameterByName("w");
ymaps.route([home, work],{avoidTrafficJams: true}).then(
function (router) {
route=router;
time = ((route.getTime())/60).toFixed(2);
var info = new Object;
info["home"] = home;
info["work"] = work;
info["time"] = ~~time+"m"+~~((time%1)*60)+"s";
JSON.stringify(info);
},
function (error) {
alert('Возникла ошибка: ' + error.message);
}
);
}
As you can see I can get a JSON string in the end. But how do I send it to clients when a request with right parameters is made?
I ended up using phantomjs and executing this js script on my php page.
I can't seem to save xml document into the marklogic with it's node-client-api. I had used the following code to try to save a dummy xml document
var marklogic = require('marklogic');
var my = require('../db/env.js');
var db = marklogic.createDatabaseClient(my.connInfo);
console.log("Write a single dummy xml document");
db.documents.write(
{
uri: '/collegiate/testxml.xml',
contentType: 'application/xml',
content: '<entry-list><entry id="horror"></entry></entry-list>'
})
Then I used the following code to retrieve it:
var marklogic = require('marklogic');
var my = require('../db/env.js');
var db = marklogic.createDatabaseClient(my.connInfo);
console.log("Read a single xml document");
db.documents.read('/collegiate/testxml.xml')
.result().then(function(document) {
//console.log('\nURI: ' + document.uri);
for (var key in document) {
console.log("key: " + key + " value: " + document.key);
}
}).catch(function(error) {
console.log(error);
});
What I get from the output is:
Read a single xml document
key: 0 value: undefined
So how to save a xml document correctly?
The issue is in the read code.
Because a client can read multiple documents, the read() request returns an array of documents.
So, try something like:
function(documents) {
for (var i=0; i < documents.length; i++) {
console.log(documents[i].content);
}
}
The repository has some examples, though the focus is on JSON documents:
https://github.com/marklogic/node-client-api/blob/master/examples/read-documents.js#L27
Hoping that helps