DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

David has posted 34 posts at DZone. View Full User Profile

Find & Replace Text in Word Document Using REST API in .NET Application

02.22.2013
| 4251 views |
  • submit to reddit
//build URI to replace text

string strURI = "http://api.saaspose.com/v1.0/words/input.docx/replaceText";
string signedURI = Sign(strURI);

//serialize the JSON request content
ReplaceText replacetext = new ReplaceText();

// set old string to replace
replacetext.OldValue = OldValue;

// set new string to replace
replacetext.NewValue = NewValue;

// True indicates case-sensitive comparison, false indicates case-insensitive comparision.

replacetext.IsMatchCase = IsMatchCase;

// True indicates the oldValue must be a standalone word.

replacetext.IsMatchWholeWord = IsMatchWholeWord;
string strJSON = JsonConvert.SerializeObject(replacetext);
Stream responseStream = ProcessCommand(signedURI, "POST", strJSON);
StreamReader reader = new StreamReader(responseStream);
string strResponse = reader.ReadToEnd();
//Parse the json string to JObject
JObject pJSON = JObject.Parse(strResponse);
ReplaceTextResponse baseResponse = JsonConvert.DeserializeObject<ReplaceTextResponse>(pJSON.ToString());
//sign URI
signedURI = Sign(baseResponse.DocumentLink.Href + "?format=doc");
//get response stream
responseStream = ProcessCommand(signedURI, "GET");
using (Stream fileStream = System.IO.File.OpenWrite(outputPath))
{
 CopyStream(responseStream, fileStream);
}
responseStream.Close();

//Here is the ReplaceText class
 
public class ReplaceText
{               
 public string OldValue { get; set; }
 public string NewValue { get; set; }
 public bool IsMatchCase { get; set; }
 public bool IsMatchWholeWord { get; set; }
}
This technical tip allows developers to replace text in Word document using Saaspose.Words REST API in your .NET applications.  Some important steps for performing this task are to build URI to replace text, serialize the JSON request content, set old string to replace, set new string to replace, Parse the json string to JObject, sign URI, get response stream and the ReplaceText class is also given in detail.

Comments

Dan Rios replied on Thu, 2013/03/14 - 5:50am