Hiding text


#1

Hi,

I need to set the .hidden property of the font for certain words within an existing word document. What is the best way of achieving this?

Many thanks,

Wayne


#2

This task, seemingly simple, is not easy to accomplish with Aspose.Words object model. The problem is well described in Roman Korchagin's blog:

http://www.aspose.com/Community/blogs/roman.korchagin/archive/2006/02/19/42026.aspx

But with some guile it can be solved although it requires a good knowledge of Aspose.Words capabilities.

The main problem is that you need to set the Font.Hidden property of a particular words in the document. But Aspose.Words as well MS Word document binary and xml formats do not deal with words - text is represented as runs which can span an arbitrary amount of text in the paragraph and sometimes the whole paragraph.

To set formatting properties for particular words in text you need to move them to separate runs.

For example, you have the following run in the text:

[The quick brown fox jumps over the lazy dog.]

If you want to hide the word 'fox' you need to distinguish it to a separate run:

[The quick brown ][fox][ jumps over the lazy dog.]

So you need to make three runs instead of one.

Here is the code that does the job of distinguishing the particular words into the separate runs and then setting the Font.Hidden property of this words to 'true'.

string filename1 = Application.StartupPath + @"\testHideWords.doc";

string filename2 = Application.StartupPath + @"\testHideWords Out.doc";

Document doc = new Document(filename1);

string searchText = "fox";

foreach (Paragraph paragraph in doc.GetChildNodes(NodeType.Paragraph, true))

{

// We are replacing the search string with /xbf symbol (inverted question mark) for temporary purposes.

// Any symbol will do that is non-special and is guaranteed not to be presented in the document.

paragraph.Range.Replace(searchText, "\xbf", true, true);

foreach (Run run in paragraph.GetChildNodes(NodeType.Run, true))

{

int pos;

while ((pos = run.Text.IndexOf("\xbf")) >=0)

{

// move the searched string into the separate run

Run runInsert = (Run)run.Clone(false);

runInsert.Text = searchText;

runInsert.Font.Hidden = true;

// make the separate run containing the text before the searched string

paragraph.ChildNodes.Insert(paragraph.ChildNodes.IndexOf(run), runInsert);

Run runBefore = (Run)run.Clone(false);

// make the initial run to contain only the text that is after the searched string

runBefore.Text = runBefore.Text.Substring(0, pos);

run.Text = run.Text.Substring(pos + 1, run.Text.Length - pos - 1);

paragraph.ChildNodes.Insert(paragraph.ChildNodes.IndexOf(runInsert), runBefore);

}

}

}

// Save resulting document.

doc.Save(filename2);

// Open saved document in MS Word.

System.Diagnostics.Process.Start(filename2);

Best regards,


#3

Exactly what I was after. It works perfectly. Thanks very much for your help.