public static void ConvertAllUrlsToHyperlinks(Word.Application wordApp) { if (wordApp.ActiveDocument == null) { return; } wordApp.ScreenUpdating = false; Word.UndoRecord ur = wordApp.UndoRecord; ur.StartCustomRecord("Convert all URLs to Hyperlinks"); try { string fulltext = wordApp.ActiveDocument.Content.Text; // this could be enormous, but processing it paragraph by pharagraph is too slow. string[] urls = UrlDetection.FindAllUrls(fulltext); Array.Sort(urls, ComapreStringsByLength); object missing = System.Type.Missing; for (int i = 0; i < urls.Length; i++) { Word.Range content = wordApp.ActiveDocument.Content; content.Find.ClearFormatting(); content.Find.Forward = false; // true causes an infinite cycle, yet that's what the example uses on msdn content.Find.Text = urls[i]; content.Find.Execute( ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); while (content.Find.Found) { if (content.Hyperlinks.Count == 0) { string url = urls[i]; if (!url.StartsWith("http://") && !url.StartsWith("https://")) { url = url.Insert(0, "http://"); } content.Hyperlinks.Add(content, url, null, url, missing, missing); } content.Find.Execute( ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } } } catch (Exception e) { } finally // The whole thing is only needed to make sure this runs (ScreenUpdate can get stuck) { wordApp.ScreenUpdating = true; ur.EndCustomRecord(); } }
public static string[] GetListOfAllUrls(Word.Document doc) { if (doc == null) { return(null); } string fulltext = doc.Content.Text; // this could be enormous, but processing it paragraph by pharagraph is too slow. return(UrlDetection.FindAllUrls(fulltext)); }