Sharepoint 2013 language translation
Translating Text (NOT regular files & sites) using SharePoint 2013 Machine Translation Service Application
Recently I came across a very simple requirement from our customer to create a ‘Plain text translation utility Webpart’ on our SharePoint 2013 portal. Presently we have components related to document translation, which is sole purpose of SP 2013 Machine Translation Service (MTS) Application.By default, all object models functionality of MTS on SharePoint 2013 (CSOM, SOM, JSOM) has support to ‘Translate’ the documents. While searching on internet we will come across many articles or documentations explaining the document translation (one good article from MSDN is over here). But there is no straight forward API function to translate the TEXT data, which can provide functionality similar to Google or Bing Text Translation.
Of course, we can tweak the existing API functions to achieve this functionality. So below mentioned code explains how we can achieve this.
//Getting the Source text from input control. string somestring = txtSource.Text; //Retreiving the Service Context of the Site SPServiceContext sc = SPServiceContext.GetContext(new SPSite("http://server/sites/MTS/")); //Converting the input text to byte array byte inputByte = Encoding.ASCII.GetBytes(somestring); //Creating Synchronised translation job with target language as SPANISH SyncTranslator job = new SyncTranslator(sc, CultureInfo.GetCultureInfo("es")); byte outputByte = null; //byte array variable to get the output. //Translate using the "Translate" function of Sync.Job with input text's byte array. //Provided a dummy file extension type as "txt" - Here we are not specifying any output file path. TranslationItemInfo itemInfo = job.Translate(inputByte, out outputByte, "txt"); //Converting the translated byte to text using UTF8 encoding. string result = Encoding.UTF8.GetString(outputByte); txtTarget.Text = result; // providing the result to the output text control.
So the trick on the above mentioned code is to use the overload for translating byte of the “Translate” function under Translation Sync.Job, then utilize the translated output byte to display the result after proper encoding.(UTF8 in this sample) to the text.
The utility webpart created using above code will look like this.