Meteor from JSON obj to CSV - node.js

I have this code which works to transform a json object into a CSV file
HTML:
<div class='mydiv'>
<textarea id="txt" class='txtarea'>[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71}]</textarea>
<button class='gen_btn'>Generate File</button>
</div>
JS:
$(document).ready(function(){
$('button').click(function(){
var data = $('#txt').val();
if(data == '')
return;
JSONToCSVConvertor(data, "Vehicle Report", true);
});
});
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
here is the code working: http://jsfiddle.net/hybrid13i/JXrwM/
the problem is that my json object is stored in a collection, anybody knows how to get the json format object printed in the client to then use the script I mentioned above?
so I want my meteor collection object to be printed in the client as a normal json example like this :
[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42},

If you want to convert a collection to an array (which is JSON) you can just use .fetch()
MyCollection.find({}).fetch();
There's also a pre-built collection-to-csv export package lfergson:exportcsv

Related

SharePoint Columns Don't Update After Successful JSOM update() call

I have a workflow that copies items from a standard Calendar list to a second standard Calendar list. But the copies contain less details about any given calendar item than the original. This works just fine except that the Start Time and End Time fields get copied over in UTC time and we need those times displayed in the user's local time zone (we have employees all over the world, so it can't be a static adjustment). I am aware that SharePoint stores all Dates/Times as UTC and I get why.
My solution to this problem is to (in the main calendar) create two hidden Date/Time columns that I would populate with the dates/times from the EventDate and EndDate Calendar columns (the UTC values), but these new values would be corrected for the time zone offset using the SharePoint Client Side Object Model (using JS). Then my workflow would copy these corrected dates/times over to the second calendar.
The following code appears to work. My success handlers are getting called for each iteration of the list items and my logged output shows all the correct values. However, after the code runs, the two Date fields that are supposed to have been updated/set on each item by the code remain blank.
<script src="/_layouts/15/sp.runtime.js"></script>
<script src="/_layouts/15/sp.js"></script>
<script>
var siteUrl = "https://duckcreek.sharepoint.com/sites/DCU";
function loadListItems(siteUrl) {
var ctx = new SP.ClientContext(siteUrl);
var oList = ctx.get_web().get_lists().getByTitle("Master Calendar");
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
// EventDate and EndDate are the pre-defined fields (from the Event
// content type) that represent the event start and end date / times
// CorrectedStartDateTime and CorrectedEndDateTime are pre-existing
// Date / Time fields in the list.
ctx.load(collListItem,
"Include(Id, DisplayName, EventDate, EndDate, CorrectedStartDateTime, CorrectedEndDateTime)");
ctx.executeQueryAsync(
Function.createDelegate(this, this.onLoadListItemsSucceeded),
Function.createDelegate(this, this.onLoadListItemsFailed));
}
function onLoadListItemsSucceeded(sender, args) {
var ctx = new SP.ClientContext(siteUrl);
var oList = ctx.get_web().get_lists().getByTitle("Master Calendar");
var listItemInfo = "";
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
// List is loaded. Enumerate the list items
let oListItem = listItemEnumerator.get_current();
// Get the Calendar item Start and End dates as stored in SharePoint (UTC)
let startDateString = oListItem.get_item("EventDate").toString();
let endDateString = oListItem.get_item("EndDate").toString();
// Get the GMT time zone offset
let startDateOffsetHours = parseInt(startDateString.split("GMT-")[1]) / 100;
let endDateOffsetHours = parseInt(endDateString.split("GMT-")[1]) / 100;
// Create new dates that are the same as the originals
let resultStartDate = new Date(startDateString);
let resultEndDate = new Date(endDateString);
// Adjust the new dates to be correct for the local time zone based on the UTC offset
resultStartDate.setHours(resultStartDate.getHours() + startDateOffsetHours);
resultEndDate.setHours(resultEndDate.getHours() + endDateOffsetHours);
// Update the two placeholder fields in the current list item with the corrected dates
oListItem.set_item("CorrectedStartDateTime", resultStartDate);
oListItem.set_item("CorrectedEndDateTime", resultEndDate);
// Update SharePoint
oListItem.update();
ctx.executeQueryAsync(
Function.createDelegate(this, this.onSetCorrectDateTimesSucceeded),
Function.createDelegate(this, this.onSetCorrectDateTimesFailed)
);
// This is just for diagnostics, but it does show the correct data.
// And since we are using .get_item() here, it would seem that we
// are pulling the correct data out of SharePoint, but the two "Corrected"
// fields remain empty after this function completes successfully.
listItemInfo += "\nDisplay name: " + oListItem.get_displayName() +
"\n\tEventDate: " + oListItem.get_item("EventDate") +
"\n\tEndDate: " + oListItem.get_item("EndDate") +
"\n\t\tCorrectedStartDateTime: " + oListItem.get_item("CorrectedStartDateTime") +
"\n\t\tCorrectedEndDateTime: " + oListItem.get_item("CorrectedEndDateTime") +
"\n--------------------------------------------------------------------------------";
}
console.log(listItemInfo.toString());
}
function onLoadListItemsFailed(sender, args) {
console.log("Request failed!" + args.get_message() + "\n" + args.get_stackTrace());
}
function onSetCorrectDateTimesSucceeded() {
console.log("Item updated!");
}
function onSetCorrectDateTimesFailed(sender, args) {
console.log("Request failed!" + args.get_message() + "\n" + args.get_stackTrace());
}
loadListItems(siteUrl);
</script>​​​
And, here is one of the records that the code produces (it actually produces one of the following for each of the items on the first calendar as it should):
Display name: NEW TEST
EventDate: Mon Dec 31 2018 19:00:00 GMT-0500 (Eastern Standard Time)
EndDate: Tue Jan 01 2019 18:59:00 GMT-0500 (Eastern Standard Time)
CorrectedStartDateTime: Tue Jan 01 2019 00:00:00 GMT-0500 (Eastern Standard Time)
CorrectedEndDateTime: Tue Jan 01 2019 23:59:00 GMT-0500 (Eastern Standard Time)
--------------------------------------------------------------------------------
However, the calendar items don't get the two "corrected" fields updated:
Simple answer
You recreate the SP.ClientContext in the onLoadListItemsSucceeded function, so you don't actually call update for the original list item. Save it in a variable and reuse it instead.
Complete code
<script src="/_layouts/15/sp.runtime.js"></script>
<script src="/_layouts/15/sp.js"></script>
<script>
var siteUrl = "https://duckcreek.sharepoint.com/sites/DCU";
var ctx;
function loadListItems(siteUrl) {
ctx = new SP.ClientContext(siteUrl);
var oList = ctx.get_web().get_lists().getByTitle("Master Calendar");
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
// EventDate and EndDate are the pre-defined fields (from the Event
// content type) that represent the event start and end date / times
// CorrectedStartDateTime and CorrectedEndDateTime are pre-existing
// Date / Time fields in the list.
ctx.load(collListItem,
"Include(Id, DisplayName, EventDate, EndDate, CorrectedStartDateTime, CorrectedEndDateTime)");
ctx.executeQueryAsync(
Function.createDelegate(this, this.onLoadListItemsSucceeded),
Function.createDelegate(this, this.onLoadListItemsFailed));
}
function onLoadListItemsSucceeded(sender, args) {
var oList = ctx.get_web().get_lists().getByTitle("Master Calendar");
var listItemInfo = "";
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
// List is loaded. Enumerate the list items
let oListItem = listItemEnumerator.get_current();
// Get the Calendar item Start and End dates as stored in SharePoint (UTC)
let startDateString = oListItem.get_item("EventDate").toString();
let endDateString = oListItem.get_item("EndDate").toString();
// Get the GMT time zone offset
let startDateOffsetHours = parseInt(startDateString.split("GMT-")[1]) / 100;
let endDateOffsetHours = parseInt(endDateString.split("GMT-")[1]) / 100;
// Create new dates that are the same as the originals
let resultStartDate = new Date(startDateString);
let resultEndDate = new Date(endDateString);
// Adjust the new dates to be correct for the local time zone based on the UTC offset
resultStartDate.setHours(resultStartDate.getHours() + startDateOffsetHours);
resultEndDate.setHours(resultEndDate.getHours() + endDateOffsetHours);
// Update the two placeholder fields in the current list item with the corrected dates
oListItem.set_item("CorrectedStartDateTime", resultStartDate);
oListItem.set_item("CorrectedEndDateTime", resultEndDate);
// Update SharePoint
oListItem.update();
ctx.executeQueryAsync(
Function.createDelegate(this, this.onSetCorrectDateTimesSucceeded),
Function.createDelegate(this, this.onSetCorrectDateTimesFailed)
);
// This is just for diagnostics, but it does show the correct data.
// And since we are using .get_item() here, it would seem that we
// are pulling the correct data out of SharePoint, but the two "Corrected"
// fields remain empty after this function completes successfully.
listItemInfo += "\nDisplay name: " + oListItem.get_displayName() +
"\n\tEventDate: " + oListItem.get_item("EventDate") +
"\n\tEndDate: " + oListItem.get_item("EndDate") +
"\n\t\tCorrectedStartDateTime: " + oListItem.get_item("CorrectedStartDateTime") +
"\n\t\tCorrectedEndDateTime: " + oListItem.get_item("CorrectedEndDateTime") +
"\n--------------------------------------------------------------------------------";
}
console.log(listItemInfo.toString());
}
function onLoadListItemsFailed(sender, args) {
console.log("Request failed!" + args.get_message() + "\n" + args.get_stackTrace());
}
function onSetCorrectDateTimesSucceeded() {
console.log("Item updated!");
}
function onSetCorrectDateTimesFailed(sender, args) {
console.log("Request failed!" + args.get_message() + "\n" + args.get_stackTrace());
}
loadListItems(siteUrl);
</script>​​​
Additional notes
Time zones offsets can be negative(-) or positive (+), so these lines are probably incomplete
// Get the GMT time zone offset
let startDateOffsetHours = parseInt(startDateString.split("GMT-")[1]) / 100;
let endDateOffsetHours = parseInt(endDateString.split("GMT-")[1]) / 100;

Need to get the data of span using protractor

I want to get the id=2504 which is in html span using protractor and display it in the console log. This id is generated dynamically so the id number can be different all the time.My code looks like :
<span class="link ng-binding" ng-click="openTrackId(mapFeedBack.reportId)">Your tracking number is 2504</span>
Please advise how can i achieve it?
You can use regex to extract numbers from a string. Look at below example code.
var id = element(by.css("span.link")).getText().then(function(text){
return text.replace(/[^0-9]+/g, "");
})
In the span text if the ID is the last thing written you can do
var textTokens = text.split(" ");
var Id = textTokens[textTokens.length - 1];
console.log(Id);
Using protractor you can do
element.all(by.tagName('span').get(0).getText().then(function(text){
textTokens = text.split(" ");
var Id = textTokens[textTokens - 1];
console.log(Id);
});
Note if you have multiple spans you can put the above code in a loop and display the Id for each span element in your console.
element.all(by.tagName('span').count().then(function(spanCount){
for (var i = 0; i < spanCount; i++){
element.all(by.tagName('span').get(i).getText().then(function(text){
textTokens = text.split(" ");
var Id = textTokens[textTokens - 1];
console.log(Id);
});
}
});

How to create Purchase Order in Netsuite with ScriptSuite?

I am new to Netsuite and I was asked to perform a script that was launched from an application programmed in java. The script with a function to generate a Purchase Order in Netsuite and other function to list the Purchase Order created earlier. It turns out that for this I am using the api SuiteScript but when creating the Purchase Order run the java application and launches the script but it gives the following error:
Aug 03, 2015 2:49:00 PM com.gargoylesoftware.htmlunit.WebClient printContentIfNecessary
INFO: {"error": {"code": "user_error", "message": "Please enter value (s) for: Vendor"}}
Javascript function to create is:
function CreatePurchase_Orders(datain){
var output = '';
nlapiLogExecution('DEBUG','createRecord','ingreso la consulta' ) ;
nlapiLogExecution('DEBUG','createRecord', 'Ingresa: '+ datain);
//var msg = validateTimeBills(datain);
var msg = null;
if (msg){
var err = new Object();
err.status = "failed";
err.message= msg;
return err;
}
var Purchase_Orders = datain.Purchase_Order;
nlapiLogExecution('DEBUG','createRecord', 'obtuvo el objeto: '+ Purchase_Orders);
for (var Purchase_Orderobject in Purchase_Orders){
var Purchase_Order = Purchase_Orders[Purchase_Orderobject];
var transdate = Purchase_Order.Transdate;
var Form = Purchase_Order.Form;
var Vendor = Purchase_Order.Vendor;
var Currency = Purchase_Order.Currency;
var Item = Purchase_Order.Item;
nlapiLogExecution('DEBUG','campos','transdate: '+ transdate+'/Form: '+Form + ' /Vendor: ' + Vendor + ' /Currency: ' + Currency
+ ' /Item: ' + Item);
var Purchase_Order = nlapiCreateRecord('purchaseorder');
var nlobjAssistant = nlapiCreateAssistant ( 'asistente' , false ) ;
var Purchase_Orderid = 1;//nlapiSubmitRecord( Purchase_Order , true, true);
if(Purchase_Order){
nlapiLogExecution('DEBUG', 'Purchase_Order ' + Purchase_Orderid + ' successfully created', '');
nlapiLogExecution('DEBUG', 'createRecord', 'creo el record');
}
Purchase_Order.setFieldValue('transdate', transdate);
Purchase_Order.setFieldValue('inpt_customform1', Form);
Purchase_Order.setFieldValue('vendor', Vendor);
Purchase_Order.setFieldValue('inpt_currency7', Currency);
Purchase_Order.setFieldValue('inpt_item', Item);
Purchase_Order.setFieldText('quantity_formattedValue', '1');
Purchase_Order.setFieldText('rate_formattedValue', '1');
Purchase_Order.setFieldText('amount_formattedValue', '1');
Purchase_Order.setFieldText('inpt_taxcode', 'VAT_MX:UNDEF_MX');
Purchase_Order.setFieldText('grossamt_formattedValue', '1');
Purchase_Order.setFieldText('tax1amt_formattedValue', '0');
Purchase_Order.setFieldText('expectedreceiptdate', '24/6/2015');
//var Purchase_Orderid = 1;//nlapiSubmitRecord( Purchase_Order , true, true);
var submitRecord = nlapiSubmitRecord(Purchase_Order);//,true);
nlapiLogExecution('DEBUG', 'submirRecord ' + submitRecord);
}
var mesg = new Object();
mesg.status = "OK";
mesg.message= nlobjAssistant.getAllFields();
return mesg;
}
And the function code in Java is:
WebClient client = new WebClient(BrowserVersion.FIREFOX_31);
client.getOptions().setJavaScriptEnabled(false);
client.getOptions().setThrowExceptionOnScriptError(false);
WebRequest requestSettings = new WebRequest(new URL(url),HttpMethod.POST);
requestSettings.setAdditionalHeader("Host", "rest.na1.netsuite.com");
requestSettings.setAdditionalHeader("User-Agent", "SuiteScript-Call");
requestSettings.setAdditionalHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
requestSettings.setAdditionalHeader("Accept-Language", " es-cl,es;q=0.8,en-us;q=0.5,en;q=0.3");
requestSettings.setAdditionalHeader("Accept-Encoding", "gzip, deflate");
requestSettings.setAdditionalHeader("Content-Type", "application/json");
requestSettings.setAdditionalHeader("Pragma", "no-cache");
requestSettings.setAdditionalHeader("Cache-Control", "no-cache");
requestSettings.setAdditionalHeader("Referer", "http://localhost:8084");
requestSettings.setAdditionalHeader("Cookie", "");
requestSettings.setAdditionalHeader("Connection", "keep-alive");
requestSettings.setAdditionalHeader("Authorization", "NLAuth nlauth_account=" + account + ", nlauth_email=" + mail + ", nlauth_signature=" + pass + ", nlauth_role=" + role + "");
Gson gson = new Gson();
//objeto llenado estaticamente de forma momentanea, se debe leer desde archivo externo
Purchase_Order purchaseOrder = new Purchase_Order("25/06/2015","formTest","vendorTest","CurrencyTest","itemTest");
String cuerpo = gson.toJson(purchaseOrder);
System.out.println(cuerpo);
// Set the request parameters
requestSettings.setRequestBody(cuerpo);
Page page = client.getPage(requestSettings);
WebResponse response = page.getWebResponse();
String json = response.getContentAsString();
System.out.println(json);
With this javascript function you should create me a record Purchase Order but I can not find the error and the solution if someone could please help me I would appreciate it a lot.
PS: if you have to create a customized form could tell me how?
thanks!
Here are some points :
As your error message says Please enter value (s) for: Vendor, you're missing the value for vendor field, which is mandatory. In your piece of code you're passing wrong internalid value for vendor. You should use entity instead of vendor
Purchase_Order.setFieldValue('entity', Vendor); // where vendor is the internal id of the vendor record
For setting custom form you can use
Purchase_Order.setFieldValue('customform', Form); // where Form is the id of the custom form
I also noticed that you're setting some values in purchase order which I suspect are to be a kind of custom one. If that is the case, then your custom field internal id should be prefixed with custbody.
For all the standard fields internal id you can refer to the Suite script Records Browser.

Error Running jsx file from Indesign to export each text frame as a .txt file

Last year my colleague helped to build a script for Indesign.
Subsequently, after a system update we no longer have the script as Indesign CS6 was reinstalled, all we have is a version as below.
Using this code in Adobe Indesign to export each text frame that begins with a particular Paragraph stylesheet "PRODUCT HEADING" however I get an error message when I run the script...
Script is based on the ExportAllStories.jsx bundled with InDesign, plus a few mods found online.
//ExportAllStories.jsx
//An InDesign CS6 JavaScript
/*
###BUILDINFO### "ExportAllStories.jsx" 3.0.0 15 December 2009
*/
//Exports all stories in an InDesign document in a specified text format.
//
//For more on InDesign scripting, go to http://www.adobe.com/products/indesign/scripting/index.html
//or visit the InDesign Scripting User to User forum at http://www.adobeforums.com
//
main();
function main(){
//Make certain that user interaction (display of dialogs, etc.) is turned on.
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
if(app.documents.length != 0){
if (app.activeDocument.stories.length != 0){
myDisplayDialog();
}
else{
alert("The document does not contain any text. Please open a document containing text and try again.");
}
}
else{
alert("No documents are open. Please open a document and try again.");
}
}
function myDisplayDialog(){
with(myDialog = app.dialogs.add({name:"ExportAllStories"})){
//Add a dialog column.
myDialogColumn = dialogColumns.add()
with(myDialogColumn){
with(borderPanels.add()){
staticTexts.add({staticLabel:"Export as:"});
with(myExportFormatButtons = radiobuttonGroups.add()){
radiobuttonControls.add({staticLabel:"Text Only", checkedState:true});
radiobuttonControls.add({staticLabel:"RTF"});
radiobuttonControls.add({staticLabel:"InDesign Tagged Text"});
}
}
}
myReturn = myDialog.show();
if (myReturn == true){
//Get the values from the dialog box.
myExportFormat = myExportFormatButtons.selectedButton;
myDialog.destroy;
myFolder= Folder.selectDialog ("Choose a Folder");
if((myFolder != null)&&(app.activeDocument.stories.length !=0)){
myExportAllStories(myExportFormat, myFolder);
}
}
else{
myDialog.destroy();
}
}
}
//myExportStories function takes care of exporting the stories.
//myExportFormat is a number from 0-2, where 0 = text only, 1 = rtf, and 3 = tagged text.
//myFolder is a reference to the folder in which you want to save your files.
function myExportAllStories(myExportFormat, myFolder){
for(myCounter = 0; myCounter < app.activeDocument.stories.length; myCounter++){
myStory = app.activeDocument.stories.item(myCounter);
myID = myStory.id;
switch(myExportFormat){
case 0:
myFormat = ExportFormat.textType;
myExtension = ".txt"
break;
case 1:
myFormat = ExportFormat.RTF;
myExtension = ".rtf"
break;
case 2:
myFormat = ExportFormat.taggedText;
myExtension = ".txt"
break;
}
if (myStory.paragraphs[0].appliedParagraphStyle.name == "PRODUCT HEADING"){
myFileName = myFileName.replace(/\s*$/,' ');
myFileName2 = myFileName.replace(/\//g, ' ');
myFilePath = myFolder + "/" + myFileName2;
myFile = new File(myFilePath);
myStory.exportFile(myFormat, myFile);
}
}
}
This results in an error on
if (myStory.paragraphs[0].appliedParagraphStyle.name == "PRODUCT HEADING"){
Any advice would be appreciated.
There is definitely a block of text with the style PRODUCT HEADING (all caps) in the Indesign File. We run Indesign CS6 as previous
thanks!
Your problem is most likely with this part: myStory.paragraphs[0]. If the story has no paragraphs this will give you an error.
You could add a condition before running this line, like this for example:
if(myStory.paragraphs.length){
if (myStory.paragraphs[0].appliedParagraphStyle.name == "PRODUCT HEADING"){
myFileName = myFileName.replace(/\s*$/,' ');
myFileName2 = myFileName.replace(/\//g, ' ');
myFilePath = myFolder + "/" + myFileName2;
myFile = new File(myFilePath);
myStory.exportFile(myFormat, myFile);
}
}

Retrieve entire Word document in task pane app / office.js

Working in Word 2013 (desktop) and office.js, we see some functionality around the user's selection (GetSelectedDataAsync, SetSelectedDataAsync), but nothing that might let you view the entire (OpenXML) document. Am I missing something?
Office.context.document.getFileAsync will let you get the entire document in a choice of 3 formats:
compressed: returns the entire document (.pptx or .docx) in Office Open XML (OOXML) format as a byte array
pdf: returns the entire document in PDF format as a byte array
text: returns only the text of the document as a string. (Word only)
Here's the example taken from MSDN:
var i = 0;
var slices = 0;
function getDocumentAsPDF() {
Office.context.document.getFileAsync("pdf", { sliceSize: 2097152 }, function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then
// result.value will return a valid File Object.
myFile = result.value;
slices = myFile.sliceCount;
document.getElementById("result").innerText = " File size:" + myFile.size + " #Slices: " + slices;
// Iterate over the file slices.
for (i = 0; i < slices; i++) {
var slice = myFile.getSliceAsync(i, function (result) {
if (result.status == "succeeded") {
doSomethingWithChunk(result.value.data);
if (slices == i) // Means it's done traversing...
{
SendFileComplete();
}
}
else
document.getElementById("result").innerText = result.error.message;
});
}
myFile.closeAsync();
}
else
document.getElementById("result2").innerText = result.error.message;
});
}
This is not exactly what you asked for (it is only the body of the document) but it helped me... So I post it here as it is where I landed when I googled my problem.
The documentation here: https://dev.office.com/reference/add-ins/word/body suggests that getOoxml() will get you the body of the document. There is also the property text which will return you the plain text content.
The way this API works is not overly straight forward - however the examples in the online doc really help in getting started.
All the best,

Resources