Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify word hyperlink with OpenXML

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

like image 284
Easy Tiger Avatar asked Aug 31 '25 16:08

Easy Tiger


1 Answers

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();
like image 77
Shelest Avatar answered Sep 02 '25 15:09

Shelest