Free Support Forum - aspose.com

How can i add hyperlinks with screentip?

Hi,

I have a query about the document format using Aspose.Words. Please see the attached document. In that I have inserted few Bookmarks(Bookmark1,Bookmark2,..etc). and there is also some hyperlinks(Suggestion:1, Suggestion:2,....etc). I set link to the different Bookmarks using these hyperlinks and you can also find some screentips with these hyperlinks.
Now I just want the same functionality using aspose.words. Does aspose support the same that I have done manually? If there is something related to this is available then please intimate me as soon as possible.

Thanks,
Prafull Gupta

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. I think that you can achieve this using InsertField method. For example see the following code.

Document doc = new Document();

DocumentBuilder builder = new DocumentBuilder(doc);

//Create format of hyperlink field

//If hyperlink target is URL then you shoul use "HYPERLINK \"{0}\" \\o \"{1}\""

string hyperlinkFormat = "HYPERLINK \\l \"{0}\" \\o \"{1}\"";

string myBookmarkName = "myBookmark";

string myScreenTip = "This is my bookmark";

string myHyperlinkText = "Link to myBookmark";

//Create field code

string hyperlinkFieldCode = string.Format(hyperlinkFormat, myBookmarkName, myScreenTip);

//Change text formation

builder.Font.Color = Color.Blue;

builder.Font.Underline = Underline.Single;

//Insert hyperlink

builder.InsertField(hyperlinkFieldCode, myHyperlinkText);

//Save output document

doc.Save(@"Test113\out.doc");

I hope this could help you.

Best regards.

Hi,

Thanks for the response. I tried the above mentioned code and it works quite well but one more enhancement that we want is to place the hyperlink at any place within the document. The above code is adding the hyperlink at the begining. Is there any way by which we can go through each sentences within the document (in each paragraph) and can place the hyperlink wherever we want...???

Hi

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. Yes of course you can place a hyperlink at any place within the document. You can use the MoveToXXX methods to move the document builder's cursor to a particular place or element in the document in order to insert there necessary elements after. Please see the following link for more information.

http://www.aspose.com/documentation/file-format-components/aspose.words-for-.net-and-java/moving-to-document-elements.html

I hope this could help you.

Best regards.

I have tried this but still I am not able to place hypelink at the place where I want. Actually we want is to place the hyprlink after sentences which have certain keywords. I will check for these words in sentence and if these were there then, add hypelink at the end of that sentence (within the paragraph something like in attached doc).
But using MoveTo() method I am always getting the hyperlink at the begining or at the end of paragraph. Please suggest where I am doing wrong or what I missing…?

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. Could you please attach your document and provide me your code? I will investigate it and try to help you.

Best regards.

I have used the code sample as you mentioned above in the same thread with some modification according to requirement. here I was matching for some keyword in the document If I match these words than, insert hyperink after word(or may be after the sentence.). You can use the same attached document (Sample Test Document.doc) for the testing.

Public Sub AddHyperLinkToSuggestedText(ByVal doc As Document)

Dim builder As DocumentBuilder = New DocumentBuilder(doc)

'Dim section As Section = New Section(oDoc)

'Create format of hyperlink field

'If hyperlink target is URL then you shoul use "HYPERLINK ""{0}"" \o ""{1}"""

Dim hyperlinkFormat As String = "HYPERLINK \l ""{0}"" \o ""{1}"""

Dim myBookmarkName As String = "BookMark1"

Dim myScreenTip As String = "You can move to bookmark using this hyperlink"

sqlCommand = New SqlCommand("Select Suggestedtext from SuggestedText", sqlConnection)

myScreenTip = sqlCommand.ExecuteScalar

Dim myHyperlinkText As String = "TestHyperLink"

'Create field code

Dim hyperlinkFieldCode As String = String.Format(hyperlinkFormat, myBookmarkName, myScreenTip)

'Change text formation

builder.Font.Color = System.Drawing.Color.Blue

builder.Font.Underline = Underline.Single

Dim paraText As String

Dim arrSplitChars As Char() = {" "c}

sqlCommand = New SqlCommand("Select keywords from MatchKeywords ", sqlConnection)

sqlConnection1.Open()

Dim sqlCommand1 As New SqlCommand()

'Dim curParagraph As Paragraph = builder.CurrentParagraph

Dim paraIndex As Integer = 0

Dim chIndex As Integer = 0

For Each section As Section In oDoc

For Each para As Paragraph In section.GetChildNodes(NodeType.Paragraph, True)

If para.HasChildNodes Then

paraText = para.Range.Text

'to process each word of the paragraph

Dim splitSentences As String() = paraText.Split(arrSplitChars, StringSplitOptions.RemoveEmptyEntries)

For Each text As String In splitSentences

dataReader = sqlCommand.ExecuteReader()

While dataReader.Read()

If text = dataReader.GetValue(0).ToString() Then

sqlCommand1 = New SqlCommand("Update MatchKeywords Set Ismatch =1 where Keywords = '" + text + "'", sqlConnection1)

sqlCommand1.ExecuteNonQuery()

builder.MoveToParagraph(paraIndex, chIndex)

builder.InsertField(hyperlinkFieldCode, myHyperlinkText)

End If

End While

dataReader.Close()

chIndex = chIndex + 1

Next

End If

chIndex = 0

paraIndex = paraIndex + 1

Next

Next

sqlConnection.Close()

End Sub

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. I think that you should use ReplaceEvaluator to achieve this. For example see the following code. This code inserts hyperlink after “Aspose” word.

public void Test154()

{

Document doc = new Document(@"Test154\in.doc");

//Create regex

Regex regex = new Regex("Aspose");

//Find word in the document

doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceEvaluator154), false);

//Save output document

doc.Save(@"Test154\out.doc");

}

private ReplaceAction ReplaceEvaluator154(object sender, ReplaceEvaluatorArgs e)

{

//Get MatchNode

Run firstRun = (Run)e.MatchNode;

//Create Run

Run secondRun = (Run)firstRun.Clone(false);

//Get index of match value

int index = firstRun.Text.IndexOf(e.Match.Value);

//Split text in match node

secondRun.Text = firstRun.Text.Substring(0, index + e.Match.Value.Length);

firstRun.Text = firstRun.Text.Substring(index + e.Match.Value.Length);

firstRun.ParentParagraph.InsertBefore(secondRun, firstRun);

DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);

//Move to first run

builder.MoveTo(firstRun);

//Insert hyperlink

//Here you should place your code to insert Hyperlink with screentip

builder.Font.Color = Color.Blue;

builder.InsertHyperlink("Aspose", "http://www.aspose.com", false);

return ReplaceAction.Skip;

}

I hope this could help you.

Best regards.

ok thanks for the suggestion, it works for me. but still there is a problem when I am using sentence at the time of creating regex (e.g. “Aspose words search” )
Regex regex = new Regex(“Aspose words search”);

// find string in the paragraph within document

para.Range.Replace(regex, new ReplaceEvaluator(ReplaceEvaluator154), false);<o:p></o:p>

and using the same ReplaceEvaluator to insert hyperlink but I am getting exception (System.ArgumentOutOfRangeException) at the line

secondRun.Text = firstRun.Text.Substring(0, index + e.Match.Value.Length);


pls suggest where I am doing wrong?

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. This can occur because your Mach.Values is placed in separate runs. Please try using the following code:

Regex regex = new Regex("Aspose words search");

//This is needed because search pattern can be represented as several runs

//after replacing it will be represented as one run

doc.Range.Replace(regex, "Aspose words search");

doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceEvaluator154), false);

Hope this helps. Also you can attach your document for testing.

Best regards.

Thanks !
Its working for me. once again thanks for the quick response.

hi, there is a problem with using above code is that the hyperlink added in the document is something like “—being employed[Suggestion 1]. Your positive—” but I needed the same thing like this “—being employed.[Suggestion 1] Your positive—” (please see the attached document).
When I am processing the same document more than once I am getting a run time error as- parsing "Those who wish to go skiing will have to do their best-something affect your decision will always be hindering you HYPERLINK \l “SuggestedBM3” \o “my screentip” - Unrecognized escape sequence \l."

I am using builder.InsertField(hyperlinkFieldCode, myHyperlinkText).
when I am processing the same document twice by modifying the added hyperlink as I need there is no error and working fine. Please suggest asap.

Thanks,

One more thing with the above post when i am processing the doc twice after few modifications both hyperlinks are apear in black color while these should be in blue (in first processing the hyperlink is apear in blue color). please let me know where i am doing wrong?

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. The above code inserts a hyperlink after the word you specified in the Regex. So if you need to insert hyperlink after dot then you can use the following Regex.

Document doc = new Document(@"Test154\in.doc");

//Create regex

Regex regex = new Regex(@"Aspose\.");

//This is needed because search pattern can be represented as several runs

//after replacing it will be represented as one run

doc.Range.Replace(regex, "Aspose.");

//Find word in the document

doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceEvaluator154), false);

//Save output document

doc.Save(@"Test154\out.doc");

Also could you please provide me code that will allow me to reproduce your problem.

Best regards.

I already tried this one by adding sentence terminator(.) after my regex string. But in case we have to place the hyperlink after the sentence which is terminated by ( ? or !) then this approach will replace previous terminators with dot(.).

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. Try using the following code:

public void Test154()

{

Document doc = new Document(@"Test154\in.doc");

//Create regex

Regex regex = new Regex(@"Aspose" + Regex.Escape(".") + "|" + Regex.Escape("?") + "|" + Regex.Escape("!"));

doc.JoinRunsWithSameFormatting();

//Find word in the document

doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceEvaluator154), true);

//Save output document

doc.Save(@"Test154\out.doc");

}

I used the latest version of Aspose.Words. The method JoinRunsWithSameFormatting was implemented in Aspose.Words.5.2.0.

Best regards.

Hi, Please see the attached document. I am trying to insert the hyperlink after first sentence in all three paragraphs. The result is fine with the second and third paragraphs but in second paragraph the hyperlink as added before the sentence terminator(?). pls suggest…
below is the code which I am using.
'sentence is a string array which have all sentences from a paragraph. I m passing first sentence as a patten in regex.
‘para is a Paragraph object for paragraphs in each section
’ the code is executed for all paragraphs in the sentences.

Dim regex As New RegularExpressions.Regex(sentence(0), RegularExpressions.RegexOptions.IgnoreCase)
para.Range.Replace(regex, sentence(0))
para.Range.Replace(regex, New ReplaceEvaluator(AddressOf InsertHyperlinkEvaluator), False)


Public Function InsertHyperlinkEvaluator(ByVal sender As Object, ByVal e As ReplaceEvaluatorArgs) As ReplaceAction
Dim hyperlinkFormat As String = “HYPERLINK \l “”{0}”" \o “”{1}"""
Dim bookmarkName As String = “BookMark1”
Dim screenTip As String=“some text for suggestion”
Dim hyperlinkText As String = " [Suggestion 1]."

Dim hyperlinkFieldCode As String = String.Format(hyperlinkFormat, bookmarkName, screenTip)

'Get MatchNode
Dim firstRun As Run = CType(e.MatchNode, Run)

'Create Run
Dim secondRun As Run = CType(firstRun.Clone(False), Run)

'Get index of match value
Dim index As Integer = firstRun.Text.IndexOf(e.Match.Value)

'Split text in match node
secondRun.Text = firstRun.Text.Substring(0, index + e.Match.Value.Length)

firstRun.Text = firstRun.Text.Substring(index + e.Match.Value.Length)

firstRun.ParentParagraph.InsertBefore(secondRun, firstRun)

Dim builder As New DocumentBuilder(e.MatchNode.Document)

'Move to first run
builder.MoveTo(firstRun)

'Insert hyperlink
builder.Font.Color = System.Drawing.Color.Blue

builder.Font.Underline = Underline.Single

builder.InsertField(hyperlinkFieldCode, hyperlinkText)

Return ReplaceAction.Skip

End Function

One more thing- when I am going to reprocess the same doc already processed document then the screentip message is added to the paragraph text in some cases while in some documents its not apear. I am not getting why so happened. can i escape the already added hyperlinks when processing second time? Please suggest…
But pls take the above problem on priority…
Thanks,

Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request.

1. You can try using the following code (You should use the latest version of Aspose.Words 5.2.0)

Dim doc As Document = New Document("testDoc2.DOC")

Dim regexString = "upon" & RegularExpressions.Regex.Escape(".") & "|" + RegularExpressions.Regex.Escape("?") & "|" & RegularExpressions.Regex.Escape("!")

Dim regex As New RegularExpressions.Regex(regexString, RegularExpressions.RegexOptions.IgnoreCase)

doc.JoinRunsWithSameFormatting()

doc.Range.Replace(regex, New ReplaceEvaluator(AddressOf InsertHyperlinkEvaluator), False)

doc.Save("out.doc")

2. You can try using the following code for removing hyperlinks form the document.

Dim doc1 As Document = New Document("out.DOC")

'Get field starts

Dim fieldStarts As NodeCollection = doc1.GetChildNodes(NodeType.FieldStart, True, False)

Dim hyperlinks As ArrayList = New ArrayList()

'Get starts of Hyperlinks

For Each start As FieldStart In fieldStarts

If (start.FieldType = FieldType.FieldHyperlink) Then

hyperlinks.Add(start)

End If

Next

'Remove hyperlinks

For Each start As FieldStart In hyperlinks

Dim currentNode As Node = start

While (currentNode.NodeType <> NodeType.FieldEnd)

currentNode = currentNode.NextSibling

currentNode.PreviousSibling.Remove()

End While

currentNode.Remove()

Next

doc1.Save("out1.doc")

Hope this helps.

Best regards.

I had tried this when u suggest the same last time but not works according to our needs. I have problem with the ReplaceEvaluator as I told you earlier.
when sentence(0)=“Ketu
movement in your fourth house of join emotions means that you lose
have a lot to think about future and introspect upon?” and when I have replace it back at line
para.Range.Replace(regex, sentence(0))
then the text of para becomes as "Ketu
movement in your fourth house of join emotions means that you lose
have a lot to think about future and introspect upon??The deep
puzzling mysteries are likely to get solved and you realize the
foolishness of being volatile."

Note that now the text contains double marks ??. In the other cases (. or !) it working fine.
And according to our requirements we need to trace each paragraphs within the document. so we are using para.Range.Replace(…) and I think for the paragraphs the method is JoinRunsWithSameFormatting() not supported.
pls suggest.