How can i modify the hypelink in Microsoft Word url from "http://www.google.com" to "MyDoc.docx" using OpenXml and .Net ?
I can obtain all hyperlinks in the document but can't find the url properties to change. I have something like this:
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(@"C:\Users\Costa\Desktop\AAA.docx", true))
{
MainDocumentPart mainPart = wordDoc.MainDocumentPart;
Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault();
}
Thanks
Unfortunately u could not directly change hyperlink path using OpenXml. The only way is to find HyperlinkRelation object for current hyperlink and replace it with hew object with same relation Id, but new hyperlink path:
using DocumentFormat.OpenXml.Wordprocessing;
MainDocumentPart mainPart = doc.MainDocumentPart;
Hyperlink hLink = mainPart.Document.Body.Descendants<Hyperlink>().FirstOrDefault();
if (hLink != null)
{
// get hyperlink's relation Id (where path stores)
string relationId = hLink.Id;
if (relationId != string.Empty)
{
// get current relation
HyperlinkRelationship hr = mainPart.HyperlinkRelationships.Where(a => a.Id == relationId).FirstOrDefault();
if (hr != null)
// remove current relation
{ mainPart.DeleteReferenceRelationship(hr); }
//add new relation with same Id , but new path
mainPart.AddHyperlinkRelationship(new System.Uri(@"D:\work\DOCS\new\My.docx", System.UriKind.Absolute), true, relationId);
}
}
// apply changes
doc.Close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With