none
Inserting HTML in Word 2016 via Office.context.document.setSelectedDataAsync, adds Machine/Junk characters. RRS feed

  • Question

  • Hi,

    I have problem with inserting Html in Word 2016 via Office.context.document.setSelectedDataAsync. It adds Machine/Junk characters beside the HTML. It happens only in Word 2016. In Word 2013 works fine.

    Hereunder is my code.

    selectedValue = '<div class="ExternalClass6C17DE219E0B4A27A2927D8A675C3EF0">
       <p class="ExternalClass59D4FF42E2F14AA3872000EFE0BEA799">​Ny frase der skal kunne indsættes på alle skabeloner</p>
       <div class="ExternalClass59D4FF42E2F14AA3872000EFE0BEA799">
          <ul>
             <li>Punkt 1</li>
             <li>Punkt 2</li>
             <li>Punkt 3</li>
          </ul>
          <ol>
             <li>Nummer 1 
                <ol>
                   <li>s</li>
                   <li>s</li>
                   <li>s</li>
                </ol>
             </li>
             <li>Nummer 2</li>
             <li>NUmmer 3</li>
          </ol>
       </div>
       <p>&#160;</p> 
       <p>&#160;</p>
       <p>Her er en tabel</p>
       <table width="100%" class="ms-rteTable-default" cellspacing="0">
          <tbody>
             <tr>
                <td class="ms-rteTable-default" style="width: 33.33%;">​1</td>
                <td class="ms-rteTable-default" style="width: 33.33%;">​2</td>
                <td class="ms-rteTable-default" style="width: 33.33%;">​3</td>
             </tr>
             <tr>
                <td class="ms-rteTable-default">​4</td>
                <td class="ms-rteTable-default">5​</td>
                <td class="ms-rteTable-default">​6</td>
             </tr>
          </tbody>
       </table>
       <p>&#160;</p>
       <h1>Her er en overskrift</h1>
       <p>&#160;</p>
       <h2>Her er en&#160;Overskrift 2</h2>
       <ol>
          <li>Et</li>
          <li>To</li>
          <li>Tre</li>
       </ol>
       <p>
          <strong>FED</strong>&#160; - 
          <em>KURSIV - </em><span style="text-decoration: underline;">UNDERSTREGET</span> - 
          <span style="text-decoration: line-through;">GENNEMSTREGET</span></p>
    </div>';
    					Office.context.document.setSelectedDataAsync(selectedValue,
                             { coercionType: Office.CoercionType.Html },
    						function (asyncResult) {
    							var error = asyncResult.error;
    							if (asyncResult.status === Office.AsyncResultStatus.Failed) {
    								$("#fraseInd").val(error.name + ": " + error.message);
    							}
    						})

    In Word 2016 it looks like this. It has added Machine or Junk characters at the last.

    Regards.

    Aftab Ahmad

    Tuesday, January 3, 2017 8:26 AM

Answers

  • Hi Celeste,

    I have finally figured it out myself. I had to add html tag with metadata and language as below. It was actually Danish characters that were giving the error. Thank for your help in regards.

    			var selectedValue1 = '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/><meta http-equiv="content-language" content="da-DK"/></head><body>' + selectedValue + '</body></html>'
    			Office.context.document.setSelectedDataAsync(selectedValue1,
    										 { coercionType: Office.CoercionType.Html },
    				function (asyncResult) {
    					var error = asyncResult.error;
    					if (asyncResult.status === Office.AsyncResultStatus.Failed) {
    						$("#fraseInd").val(error.name + ": " + error.message);
    					}
    				})
    		});



    Regards.

    Aftab Ahmad


    • Edited by Aftab Ahmad- Tuesday, January 17, 2017 9:51 AM
    • Marked as answer by Aftab Ahmad- Tuesday, January 17, 2017 9:51 AM
    Tuesday, January 17, 2017 9:50 AM

All replies

  • Hi,

    What editor do you use to develop?

    I could insert the HTML without redundant characters in Office2016/VS2015 by the code below.

    What is your specific version of Office?

    I suggest you use Visual Studio to check if it would add junk characters.

        function writeHtmlData() {
            var selectedValue = "<div class=\"ExternalClass6C17DE219E0B4A27A2927D8A675C3EF0\"><p class=\"ExternalClass59D4FF42E2F14AA3872000EFE0BEA799\">Ny frase der skal kunne indsættes på alle skabeloner</p><div class=\"ExternalClass59D4FF42E2F14AA3872000EFE0BEA799\"><ul><li>Punkt 1</li><li>Punkt 2</li><li>Punkt 3</li></ul><ol><li>Nummer 1 <ol><li>s</li><li>s</li><li>s</li></ol></li><li>Nummer 2</li><li>NUmmer 3</li></ol>   </div>   <p>&#160;</p>    <p>&#160;</p>   <p>Her er en tabel</p>   <table width=\"100%\" class=\"ms-rteTable-default\" cellspacing=\"0\">      <tbody>         <tr>            <td class=\"ms-rteTable-default\" style=\"width: 33.33%;\">1</td>            <td class=\"ms-rteTable-default\" style=\"width: 33.33%;\">2</td>            <td class=\"ms-rteTable-default\" style=\"width: 33.33%;\">3</td>         </tr>         <tr>            <td class=\"ms-rteTable-default\">4</td>            <td class=\"ms-rteTable-default\">5</td>            <td class=\”ms-rteTable-default\”>6</td>         </tr>      </tbody>   </table>   <p>&#160;</p>   <h1>Her er en overskrift</h1>   <p>&#160;</p>   <h2>Her er en&#160;Overskrift 2</h2>   <ol>      <li>Et</li>      <li>To</li>      <li>Tre</li>   </ol>   <p>      <strong>FED</strong>&#160; -       <em>KURSIV - </em><span style=\"text-decoration: underline;\">UNDERSTREGET</span> -       <span style=\"text-decoration: line-through;\">GENNEMSTREGET</span></p></div>";
            var report = document.getElementById("status");
            Office.context.document.setSelectedDataAsync(selectedValue, { coercionType: Office.CoercionType.Html },
                function (asyncResult) {
                    // Tell the user we succeeded and then clear the message after a 2 second delay
                    if (asyncResult.status == Office.AsyncResultStatus.Succeeded) {
                        report.innerText = "Succeeded";
                        setTimeout(function () {
                            report.innerText = "";
                        }, 2000);
                    }
                });
        }

    Regards,

    Celeste


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, January 4, 2017 5:57 AM
    Moderator
  • Hi Celeste,

    Thank you for the answer.

    It has still the same error. I am using Visual Studio 2015 with Word 2016. I don't use any other editor than Visual Studio.

    As I written before that it works fine in Word 2013. The error comes only in Word 2016. There must be an error in Word 2016.

    Any other idea?

    Regards

    Aftab Ahmad

    Wednesday, January 4, 2017 8:28 PM
  • Hi,

    How do you declare the variable like you shared? I think the variable you declared could not be recognized by visual studio.

    If you test with code in my first post, would it perform well?

    The code works fine in Version1612(Build 7668.2033) and Version 1609(Build 7369.2095) and 16.0.6965.2115.

    What is your specific version?

    If possible, I suggest you share a sample project with us for testing.

    Regards,

    Celeste


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, January 5, 2017 6:35 AM
    Moderator
  • Hi Celeste,

    This is my whole JS file. I have tried to clean classes attributes but still the same error.

    var selectedValue = '';
    $(document).ready(function () {
    	var table = $('#phrasesTable').DataTable({
    		"bPaginate": false,
    		"bInfo": false,
    		"dom": '<"toolbar">frtip'
    	});
    			
    	//$('div.dataTables_filter label:contains("Search:")').html($('div.dataTables_filter label:contains("Search:")').html().split("Search:").join(""))
    	$('div.dataTables_filter input').attr('placeholder', 'Søg frase');
    	$(function () {
    		$("div.toolbar").html('<input type="button" value="Indsæt frase" id="fraseInd" />');
    			
    		$('#fraseInd').click(function () {
    			selectedValue = '<div class="ExternalClass6C17DE219E0B4A27A2927D8A675C3EF0">' +
    			'   <p class="ExternalClass59D4FF42E2F14AA3872000EFE0BEA799">​Ny frase der skal kunne indsættes på alle skabeloner</p>' +
    			'   <div class="ExternalClass59D4FF42E2F14AA3872000EFE0BEA799">' +
    			'	  <ul>' +
    			'		 <li>Punkt 1</li>' +
    			'		 <li>Punkt 2</li>' +
    			'		 <li>Punkt 3</li>' +
    			'	  </ul>' +
    			'	  <ol>' +
    			'		 <li>Nummer 1 ' +
    			'			<ol>+ ' +
    			'			   <li>s</li>' +
    			'			   <li>s</li>' +
    			'			   <li>s</li>' +
    			'			</ol>' +
    			'		 </li>' +
    			'		 <li>Nummer 2</li>' +
    			'		 <li>NUmmer 3</li>' +
    			'	  </ol>' +
    			'   </div>' +
    			'   <p>&#160;</p> ' +
    			'   <p>&#160;</p>' +
    			'   <p>Her er en tabel</p>' +
    			'   <table width="100%" class="ms-rteTable-default" cellspacing="0">' +
    			'	  <tbody>' +
    			'		 <tr>' +
    			'			<td class="ms-rteTable-default" style="width: 33.33%;">​1</td>' +
    			'			<td class="ms-rteTable-default" style="width: 33.33%;">​2</td>' +
    			'			<td class="ms-rteTable-default" style="width: 33.33%;">​3</td>' +
    			'		 </tr>' +
    			'		 <tr>' +
    			'			<td class="ms-rteTable-default">​4</td>' +
    			'			<td class="ms-rteTable-default">5​</td>' +
    			'			<td class="ms-rteTable-default">​6</td>' +
    			'		 </tr>' +
    			'	  </tbody>' +
    			'   </table>' +
    			'   <p>&#160;</p>' +
    			'   <h1>Her er en overskrift</h1>' +
    			'   <p>&#160;</p>' +
    			'   <h2>Her er en&#160;Overskrift 2</h2>' +
    			'   <ol>' +
    			'	  <li>Et</li>' +
    			'	  <li>To</li>' +
    			'	  <li>Tre</li>' +
    			'   </ol>' +
    			'   <p>' +
    			'	  <strong>FED</strong>&#160; - ' +
    			'	  <em>KURSIV - </em><span style="text-decoration: underline;">UNDERSTREGET</span> - ' +
    			'	  <span style="text-decoration: line-through;">GENNEMSTREGET</span></p>' +
    			'</div>';
    			var htmlobj = $(selectedValue);
    			recursiveEachRemoveClass(htmlobj);
    			//htmlobj.removeClass();
    			//htmlobj.each(function() {
    			//	$(this).removeAttr('class');
    			//});
    			selectedValue = htmlobj.html().replaceAll('#160;', '').replaceAll('&nbsp;', '');
    			Office.context.document.setSelectedDataAsync(selectedValue,
    										 { coercionType: Office.CoercionType.Html },
    				function (asyncResult) {
    					var error = asyncResult.error;
    					if (asyncResult.status === Office.AsyncResultStatus.Failed) {
    						$("#fraseInd").val(error.name + ": " + error.message);
    					}
    				})
    		});
    		$.each($('#phrasesBody td').not(':empty'), function (i, v) {
    				    
    			$(v).html("<div class='PhraseDiv'>" + $(v).text()+"</div>");
    				    
    		});
    		$('#fraseInd').prop("disabled", true);
    		$(".dataTables_filter input").keypress(function () {
    			$('#fraseInd').prop("disabled", true);
    		});
    	});
    
    	$('#phrasesTable tbody').on('click', 'tr', function () {
    		if ($(this).hasClass('selected')) {
    			try {
    				selectedValue = '';
    				$(this).removeClass('selected');
    				$('#fraseInd').prop("disabled", true);
    				$('#fraseInd').removeClass('SelectedButton');
    						
    			} catch (e) {
    				$('#fraseInd').val(e.toString());
    						
    			}
    		}
    		else {
    			selectedValue = $(this).find("td").eq(1).attr('title'); //decodeEntities();
    			//selectedValue = $(this).find("td").eq(1).text();
    			table.$('tr.selected').removeClass('selected');
    			$(this).addClass('selected');
    			$('#fraseInd').prop("disabled", false);
    			$('#fraseInd').addClass('SelectedButton');
    		}
    	});
    
    	if ($("#hdnXmlPath").length) {
    		$("#btnSaveClient").show();
    	}
    
    	if ($("#hdnXmlPath").length) {
    		$("#btnRefreshPhrases1").show();
    	}
    
    	if ($("#hdnEboks").length && $("#hdnEboks").val() == "Y") {
    		$("#btnSaveEboksClient").show();
    	}
    
    	//$('#button').click(function () {
    	//	table.row('.selected').remove().draw(false);
    	//});
    });
    
    function recursiveEachRemoveClass(element) {
    	element.removeClass();
    	element.removeAttr('class');
    	element.children().each(function () {
    		var currentElement = $(this);
    		//////////// Loop her children
    		recursiveEachRemoveClass(currentElement);
    	});
    }
    
    function decodeEntities(encodedString) {
    	return $.trim($("<textarea/>").html(encodedString).val().replace(/[\t\n]+/g, ' '));
    	//var div = document.createElement('div');
    	//div.innerHTML = encodedString;
    	//return div.innerHTML();
    }
    
    String.prototype.replaceAll = function (search, replacement) {
    	var target = this;
    	return target.replace(new RegExp(search, 'g'), replacement);
    };
    
    function startDocumentProcess(fileType, buttonType)
    {
    	//$("#imgWaiting").show();
    	//$("#WaitDialog").dialog({
    	//	modal: true,
    	//	closeOnEscape: false,
    	//	open: function (event, ui) { $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); }
    	//});
    	getDocumentAsCompressed(fileType, buttonType);
    }
    
    // Gets the document content in base64 
    // (using getFileAsync), works in Word and PowerPoint. 
    function getDocumentAsCompressed1(fileType, buttonType) {
    	var fileContent;
    	Office.context.document.getFileAsync(
    					fileType,
    					function (result) {
    						var myFile = result.value;
    						myFile.getSliceAsync(
    								0,
    								function (result) {
    									if (result.status == "succeeded")
    										fileContent =
    												OSF.OUtil.encodeBase64(
    														result.value.data
    														);
    								});
    					});
    }
    
    function getDocumentAsCompressed(fileType, buttonType) {
    	try {
    		$("#lblError").hide();
    		Office.context.document.getFileAsync(fileType, { sliceSize: 65536 /*64 KB*/ },
    				function (result) {
    					if (result.status == "succeeded") {
    						// If the getFileAsync call succeeded, then
    						// result.value will return a valid File Object.
    						var myFile = result.value;
    						var sliceCount = myFile.sliceCount;
    						var slicesReceived = 0, gotAllSlices = true, docdataSlices = [];
    						//app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);
    
    						// Get the file slices.
    						getSliceAsync(myFile, 0, sliceCount, gotAllSlices, docdataSlices, slicesReceived, fileType, buttonType);
    					}
    					else {
    						showError(result.error.message);
    						//app.showNotification("Error:", result.error.message);
    					}
    				});
    	} catch (e) {
    		updateNodeValue("documentgenerated", "N");
    		showError(e.toString());
    	}
    }
    
    function getSliceAsync(file, nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived, fileType, buttonType) {
    	file.getSliceAsync(nextSlice, function (sliceResult) {
    		if (sliceResult.status == "succeeded") {
    			if (!gotAllSlices) { // Failed to get all slices, no need to continue.
    				return;
    			}
    
    			// Got one slice, store it in a temporary array.
    			// (Or you can do something else, such as
    			// send it to a third-party server.)
    			docdataSlices[sliceResult.value.index] = sliceResult.value.data;
    			if (++slicesReceived == sliceCount) {
    				// All slices have been received.
    				file.closeAsync();
    				onGotAllSlices(docdataSlices, fileType, buttonType);
    			}
    			else {
    				getSliceAsync(file, ++nextSlice, sliceCount, gotAllSlices, docdataSlices, slicesReceived, fileType, buttonType);
    			}
    		}
    		else {
    			gotAllSlices = false;
    			file.closeAsync();
    			updateNodeValue("documentgenerated", "N");
    			showError("getSliceAsync Error:" + sliceResult.error.message);
    			//app.showNotification("getSliceAsync Error:", sliceResult.error.message);
    		}
    	});
    }
    
    // Converts an ArrayBuffer directly to base64, without any intermediate 'convert to string then
    // use window.btoa' step. According to my tests, this appears to be a faster approach:
    // http://jsperf.com/encoding-xhr-image-data/5
    
    function base64ArrayBuffer(arrayBuffer) {
    	var base64 = ''
    	var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    
    	var bytes = new Uint8Array(arrayBuffer)
    	var byteLength = bytes.byteLength
    	var byteRemainder = byteLength % 3
    	var mainLength = byteLength - byteRemainder
    
    	var a, b, c, d
    	var chunk
    
    	// Main loop deals with bytes in chunks of 3
    	for (var i = 0; i < mainLength; i = i + 3) {
    		// Combine the three bytes into a single integer
    		chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
    
    		// Use bitmasks to extract 6-bit segments from the triplet
    		a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
    		b = (chunk & 258048) >> 12 // 258048   = (2^6 - 1) << 12
    		c = (chunk & 4032) >> 6 // 4032     = (2^6 - 1) << 6
    		d = chunk & 63               // 63       = 2^6 - 1
    
    		// Convert the raw binary segments to the appropriate ASCII encoding
    		base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
    	}
    
    	// Deal with the remaining bytes and padding
    	if (byteRemainder == 1) {
    		chunk = bytes[mainLength]
    
    		a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
    
    		// Set the 4 least significant bits to zero
    		b = (chunk & 3) << 4 // 3   = 2^2 - 1
    
    		base64 += encodings[a] + encodings[b] + '=='
    	} else if (byteRemainder == 2) {
    		chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
    
    		a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
    		b = (chunk & 1008) >> 4 // 1008  = (2^6 - 1) << 4
    
    		// Set the 2 least significant bits to zero
    		c = (chunk & 15) << 2 // 15    = 2^4 - 1
    
    		base64 += encodings[a] + encodings[b] + encodings[c] + '='
    	}
    
    	return base64
    }
    
    function b64EncodeUnicode(str) {
    	return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
    		return String.fromCharCode('0x' + p1);
    	}));
    }
    
    function onGotAllSlices(docdataSlices, fileType, buttonType) {
    	try {
    		var docdata = [];
    		for (var i = 0; i < docdataSlices.length; i++) {
    			docdata = docdata.concat(docdataSlices[i]);
    		}
    
    		//var fileContent = new String();
    		//for (var j = 0; j < docdata.length; j++) {
    		//	fileContent += String.fromCharCode(docdata[j]);
    		//}
    
    		if (fileType == Office.FileType.Compressed) {
    			uploadFile(fileType, buttonType, docdata);
    			getDocumentAsCompressed(Office.FileType.Pdf, buttonType);
    		}
    		else {
    			uploadFile(fileType, buttonType, docdata);
    		}
    
    		//updateNodeValue("documentgenerated", "N");
    		//$("#lblErrorText").html(fileContent);
    		// Now all the file content is stored in 'fileContent' variable,
    		// you can do something with it, such as print, fax...
    	} catch (e) {
    		updateNodeValue("documentgenerated", "N");
    		showError(e.toString());
    	}
    }
    
    function updateNodeValue(nodename, nodeValue) {
    	var nameSpace = "http://www.gfforsikring.dk/gfbrev";
    	Office.context.document.customXmlParts.getByNamespaceAsync(nameSpace, function (asyncResult1) {
    		// Get the client-level node
    		if (asyncResult1.value != null && asyncResult1.value.length > 0) {
    			asyncResult1.value[0].getNodesAsync("/ns0:gfforsikring[1]/ns0:wordintegration[1]/ns0:" + nodename + "[1]", function (asyncResult2) {
    				asyncResult2.value[0].setXmlAsync("<" + nodename + " xmlns='" + nameSpace + "'>" + nodeValue + "</" + nodename + ">");
    			});
    		}
    	});
    }
    
    $(document).ajaxStart(function () {
    	$('.modal').show();
    }).ajaxStop(function () {
    	$('.modal').css("background","rgba( 255, 255, 255, .9 )");
    });
    
    function uploadFile(fileType, buttonType, docdata) {
    		    
    	var fileNameWithExtension = $("#hdnTemplateName").val();
    	var fileExtension = "";
    	if (fileType == Office.FileType.Compressed)
    		fileExtension = ".docx";
    	else
    		fileExtension = ".pdf";
    
    	$("#lblSavingToTia").html("Vent venligst......")
    	var options = {};
    	options.url = "UploadFile.ashx";
    	options.type = "POST";
    	options.headers = {
    		'FilePath': fileNameWithExtension + fileExtension,
    		'SendToEboks': buttonType,
    		'XmlFile': $("#hdnXmlFile").val(),
    		'CurrentUser': $("#hdnCurrentUser").val(),
    		'Content-Type': 'application/json'
    	};
    	options.data = base64ArrayBuffer(docdata); //OSF.OUtil.encodeBase64(docdata);
    	options.contentType = false;
    	options.processData = false;
    	options.success = function (result) {
    		if (fileType != Office.FileType.Compressed) {
    			$("#imgWaiting").hide();
    			$("#divProcessCompleted").show();
    			$("#lblSavingToTia").html("<i class='glyphicon glyphicon-ok' style='margin-right: 10px;'></i> Dit brev er nu gemt i TIA. Du kan lukke Word eller sende brevet via e-mail. Hvis du vil sende brevet som e-mail, " +
    				"så klik på ikonet \"Send brev som e-mail\" i værktøjslinjen.")
    			updateNodeValue("documentgenerated", "Y");
    			updateNodeValue("pdfcontent", encodeURIComponent(result));
    
    			//$("#lnkpdf").attr("href", "#");
    			//$("#lnkpdf").attr("target", "_blank");
    			//$("#lnkpdf").attr("href", "file:/" + fileNameWithExtension + fileExtension);
    			//$("#lnkpdf").html(fileNameWithExtension + fileExtension);
    		}
    		//				else {
    		//$("#lnkdocx").attr("href", "#");
    		//$("#lnkdocx").attr("target", "_blank");
    		//$("#lnkdocx").attr("href", "file:/" + fileNameWithExtension + fileExtension);
    		//$("#lnkdocx").html(fileNameWithExtension + fileExtension);
    		//				}
    	};
    	options.error = function (err) {
    		showError(err.statusText);
    		$("#imgWaiting").hide();
    		$("#divProcessCompleted").hide();
    		$('.modal').hide();
    		updateNodeValue("documentgenerated", "N");
    	};
    
    	$.ajax(options);
    			
    }
    
    function showError(message)
    {
    	$("#lblError").html(message);
    	$("#lblError").show();
    }

    Regards.

    Aftab Ahmad

    Friday, January 6, 2017 11:04 AM
  • Hi,

    I test with the part to insert the button and the click event. It still works fine for me.

    If you add the button at design time, would it be different?

    I would suggest you comment out other code and test the part separately to check if the issue causes from setSelectedDataAsync method or the rest part in your code.

    Regards,

    Celeste


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, January 13, 2017 9:38 AM
    Moderator
  • Hi Celeste,

    I have finally figured it out myself. I had to add html tag with metadata and language as below. It was actually Danish characters that were giving the error. Thank for your help in regards.

    			var selectedValue1 = '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/><meta http-equiv="content-language" content="da-DK"/></head><body>' + selectedValue + '</body></html>'
    			Office.context.document.setSelectedDataAsync(selectedValue1,
    										 { coercionType: Office.CoercionType.Html },
    				function (asyncResult) {
    					var error = asyncResult.error;
    					if (asyncResult.status === Office.AsyncResultStatus.Failed) {
    						$("#fraseInd").val(error.name + ": " + error.message);
    					}
    				})
    		});



    Regards.

    Aftab Ahmad


    • Edited by Aftab Ahmad- Tuesday, January 17, 2017 9:51 AM
    • Marked as answer by Aftab Ahmad- Tuesday, January 17, 2017 9:51 AM
    Tuesday, January 17, 2017 9:50 AM