Snippets


https://github.com/OfficeDev/office-js-snippet-explorer



Inserting formatted text, html, ooxml (Office Open XML) on the current selection
Formatting an existing paragraph, font, size, color, highlight color, style, etc.
Changing paragraph properties (i.e. alignment, indentation, etc)
Inserting Paragraphs
Append/Prepend text to paragraphs
Traversing the document's or section's paragraphs
Wrapping a paragraph with a content control
Getting a collection of content controls by tag or title (or all)
Setting Content Control Properties
Clear document body content
Insert content on the header/footer of the document
Insert an inline picture
Search, plain text and using wild cards



Writing Text

Write text to the current user selection

Office.context.document.setSelectedDataAsync("Hello World!", 
                                              function (asyncResult) {
  if (asyncResult.status == "failed") {
    showMessage("Action failed with error: " + asyncResult.error.message);
  }
});

Reading Text

Read text from the user current selection

Office.context.document.getSelectedDataAsync("text", 
                                             function (asyncResult) {
  if (asyncResult.status == "failed") {
    showMessage("Action failed with error: " + asyncResult.error.message);
  }
  else {
    showMessage("Selected data: " + asyncResult.value);
  }
});


function doSomething() { 
Word.run(function (context) {
// get selection
var selection = context.document.getSelection();
// load the text of all paragraphs in the selection
var paragraphs = selection.paragraphs.load('text');

var paragraph = range.insertParagraph("Customer", Word.InsertLocation.before);
paragraph.styleBuiltIn = "Heading1";




clear the contents of the body.
var body = ctx.document.body;
body.clear();



load the text in document body.
var body = context.document.body;
context.load(body, 'text');


insert a page break at the start of the document body.
var body = ctx.document.body;
body.insertBreak(Word.BreakType.page, Word.InsertLocation.start);



wrap the body in a content control.
var body = ctx.document.body;
body.insertContentControl();



insert base64 encoded .docx at the beginning of the content body.
var body = ctx.document.body;
body.insertFileFromBase64(getBase64(), Word.InsertLocation.start);



insert HTML in to the beginning of the body.
var body = ctx.document.body;
body.insertHtml('<strong>This is text inserted with body.insertHtml()</strong>', Word.InsertLocation.start);



insert OOXML in to the beginning of the body.
var body = ctx.document.body;
body.insertOoxml("<w:p xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml'><w:r><w:rPr><w:b/><w:b-cs/><w:color w:val='FF0000'/><w:sz w:val='28'/><w:sz-cs w:val='28'/></w:rPr><w:t>Hello world (this should be bold, red, size 14).</w:t></w:r></w:p>", Word.InsertLocation.start);


insert the paragraph at the end of the document body.
var body = ctx.document.body;
body.insertParagraph('Content of a new paragraph', Word.InsertLocation.end);



insert text in to the beginning of the body.
var body = ctx.document.body;
body.insertText('This is text inserted with body.insertText()', Word.InsertLocation.start);



load font and style information for the document body.
var body = ctx.document.body;
context.load(body, 'font/size, font/name, font/color, style');



Searching
Word.run(function (context) {

// Create a proxy object for the document body.
var body = context.document.body;

// Setup the search options.
var options = Word.SearchOptions.newObject(context);
options.matchCase = false


// Queue a commmand to search the document.
var searchResults = context.document.body.search('video', options);


// Queue a commmand to load the results.
context.load(searchResults, 'text, font');


// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
var results = 'Found count: ' + searchResults.items.length +
'; we highlighted the results.';


// Queue a command to change the font for each found item.
for (var i = 0; i < searchResults.items.length; i++) {
searchResults.items[i].font.color = '#FF0000' // Change color to Red
searchResults.items[i].font.highlightColor = '#FFFF00';
searchResults.items[i].font.bold = true;
}

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log(results);
});
});
})
.catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});



Content Controls
Word.run(function (context) {

// Create a proxy object for the content controls collection.
var contentControls = context.document.contentControls;

// Queue a command to load the content controls collection.
contentControls.load('text');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {

if (contentControls.items.length === 0) {
console.log("There isn't a content control in this document.");
} else {

// Queue a command to clear the contents of the first content control.
contentControls.items[0].clear();
// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('Content control cleared of contents.');
});
}

});
})



Create a content control
Word.run(function (context) {

// Create a proxy range object for the current selection.
var range = context.document.getSelection();

// Queue a commmand to create the content control.
var myContentControl = range.insertContentControl();
myContentControl.tag = 'Customer-Address';
myContentControl.title = 'Enter Customer Address Here:';
myContentControl.style = 'Heading 2';
myContentControl.insertText('One Microsoft Way, Redmond, WA 98052', 'replace');
myContentControl.cannotEdit = true;
myContentControl.appearance = 'tags';

// Queue a command to load the id property for the content control you created.
context.load(myContentControl, 'id');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('Created content control with id: ' + myContentControl.id);
});
})



//get all content controls
Word.run(function (context) {

// Create a proxy object for the content controls collection.
var contentControls = context.document.contentControls;

// Queue a command to load the id property for all of content controls.
context.load(contentControls, 'id');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
// Show the id property for each content control.
for (var i = 0; i < contentControls.items.length; i++) {
console.log("contentControl[" + i + "].id = " +
contentControls.items[i].id);
}
});
})




the content controls collection that contains a specific tag.
var contentControlsWithTag = context.document.contentControls.getByTag('Customer-Address');

// Queue a command to load the text property for all of content controls with a specific tag.
context.load(contentControlsWithTag, 'text');



// get html from a content control
Word.run(function (context) {

// Create a proxy object for the content controls collection that contains a specific tag.
var contentControlsWithTag = context.document.contentControls.getByTag('Customer-Address');

// Queue a command to load the tag property for all of content controls.
context.load(contentControlsWithTag, 'tag');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
if (contentControlsWithTag.items.length === 0) {
console.log('No content control found.');
}
else {
// Queue a command to get the HTML contents of the first content control.
var html = contentControlsWithTag.items[0].getHtml();


get the OOXML contents of the first content control.
var ooxml = contentControls.items[0].getOoxml();

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync()
.then(function () {
console.log('Content control HTML: ' + html.value);
});
}
});
})


// insert page break after content control
Word.run(function (context) {

// Create a proxy object for the content controls collection.
var contentControls = context.document.contentControls;

// Queue a commmand to load the id property for all of content controls.
context.load(contentControls, 'id');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion. We now will have
// access to the content control collection.
return context.sync().then(function () {
if (contentControls.items.length === 0) {
console.log('No content control found.');
}
else {
// Queue a command to insert a page break after the first content control.
contentControls.items[0].insertBreak('page', "After");


// Queue a command to put HTML into the contents of the first content control.
contentControls.items[0].insertHtml('<strong>HTML content inserted into the content control.</strong>', 'Start');


// Queue a command to insert a paragraph after the first content control.
contentControls.items[0].insertParagraph('Text of the inserted paragraph.', 'After');


// Queue a command to replace text in the first content control.
contentControls.items[0].insertText('Replaced text in the first content control.', 'Replace');



// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync()
.then(function () {
console.log('Inserted a page break after the first content control.');
});
}
});
})



displaying content controls
Word.run(function (context) {

// Create a proxy object for the content controls collection.
var contentControls = context.document.contentControls;

// Queue a command to load the id property for all of the content controls.
context.load(contentControls, 'id');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
if (contentControls.items.length === 0) {
console.log('No content control found.');
}
else {
// Queue a command to load the properties on the first content control.
contentControls.items[0].load( 'appearance,' +
'cannotDelete,' +
'cannotEdit,' +
'color,' +
'id,' +
'placeHolderText,' +
'removeWhenEdited,' +
'title,' +
'text,' +
'type,' +
'style,' +
'tag,' +
'font/size,' +
'font/name,' +
'font/color');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync()
.then(function () {
console.log('Property values of the first content control:' +
' ----- appearance: ' + contentControls.items[0].appearance +
' ----- cannotDelete: ' + contentControls.items[0].cannotDelete +
' ----- cannotEdit: ' + contentControls.items[0].cannotEdit +
' ----- color: ' + contentControls.items[0].color +
' ----- id: ' + contentControls.items[0].id +
' ----- placeHolderText: ' + contentControls.items[0].placeholderText +
' ----- removeWhenEdited: ' + contentControls.items[0].removeWhenEdited +
' ----- title: ' + contentControls.items[0].title +
' ----- text: ' + contentControls.items[0].text +
' ----- type: ' + contentControls.items[0].type +
' ----- style: ' + contentControls.items[0].style +
' ----- tag: ' + contentControls.items[0].tag +
' ----- font size: ' + contentControls.items[0].font.size +
' ----- font name: ' + contentControls.items[0].font.name +
' ----- font color: ' + contentControls.items[0].font.color);
});
}
});
})



inserting html into the selection
var htmlText =
'<h1><strong>Insert Html</strong></h1>' +
'<h2><em>Office Extensibility Platform</em></h2>' +
'<p>This is an example of how the InsertHtml method works.</p>' +
'<table>' +
'<tr><td>Check</td><td>out</td></tr>' +
'<tr><td>this</td><td>table</td></tr>' +
'</table>';

// Create a range proxy object for the current selection.
var range = context.document.getSelection();

// Queue a commmand to insert HTML at the end of the selection.
range.insertHtml(htmlText, Word.InsertLocation.end);



inserting ooxml into the selection
var ooxmlText = "<w:p xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml'>" +
"<w:r><w:rPr><w:b/><w:b-cs/><w:color w:val='FF0000'/><w:sz w:val='28'/><w:sz-cs w:val='28'/>" +
"</w:rPr><w:t>Hello world (this should be bold, red, size 14).</w:t></w:r></w:p>";

// Create a range proxy object for the current selection.
var range = context.document.getSelection();

// Queue a commmand to insert OOXML at the end of the selection.
range.insertOoxml(ooxmlText, Word.InsertLocation.end);




// inserting text into the selection
var textSample = 'This is an example of the insert text method. This is a method ' +
'which allows users to insert text into a selection.';

// Create a range proxy object for the current selection.
var range = context.document.getSelection();

// Queue a commmand to insert text at the end of the selection.
range.insertText(textSample, Word.InsertLocation.end);



save a document
Word.run(function (context) {

// Create a proxy object for the document.
var thisDocument = context.document;


// Queue a commmand to load the document save state (on the saved property).
context.load(thisDocument, 'saved');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {

if (thisDocument.saved === false) {
// Queue a command to save this document.
thisDocument.save();

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('Saved the document');
});
} else {
console.log('The document has not changed since the last save.');
}
});
})



change the current selection's font name.
var selection = context.document.getSelection();
selection.font.name = 'Arial';
selection.font.bold = true;




Word.run(function (context) {

// Create a proxy object for the paragraphs collection.
var paragraphs = context.document.body.paragraphs;

// Queue a commmand to load the style property for all of the paragraphs.
context.load(paragraphs, 'style');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {

// Queue a command to clear the contents of the first paragraph.
paragraphs._GetItem(0).clear();

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('Cleared the contents of the first paragraph.');
});
});
})



format line spacing
Word.run(function (context) {

// Create a proxy object for the paragraphs collection.
var paragraphs = context.document.body.paragraphs;

// Queue a commmand to load the style property for all of the paragraphs.
context.load(paragraphs, 'style');

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {

// Create a proxy object for the first paragraph.
var paragraph = paragraphs._GetItem(0);

// Queue a change to the paragraph's line spacing.
paragraph.linespacing = 36;

// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('Changed the paragraph line spacing.');
});
});
})




© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext