Add Hyperlinks to a Word Document with Open XML | Quisitive
Add Hyperlinks to a Word Document with Open XML
April 21, 2011
Quisitive

I know you’ve been thirsty for some code, so here we go.

I was dumfounded at the absence of “working” code samples for injecting a hyperlink using Open XML 2.0 on google and bing.  I don’t consider samples that reference missing sealed constant classes to be “working”…

This one injects a hyperlink at the end of the word doc and will not inject it more than once:

//c:Program Files (x86)Open XML SDKV2.0libDocumentFormat.OpenXml.dll
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using (WordprocessingDocument wdPackage =
WordprocessingDocument.Open(stream, true))
{
    //add the url
    string urlLabel = "Text To Display";
    System.Uri uri = new Uri("http://something.urlencoded.org");
    bool urlExists = false;

    foreach (HyperlinkRelationship hRel in wdPackage.MainDocumentPart.HyperlinkRelationships)
    {

        if (hRel.Uri == uri)
        {
            urlExists = true;
            break;
        }
    }


    if (!urlExists)
    {
        MainDocumentPart mainPart = wdPackage.MainDocumentPart;
        HyperlinkRelationship rel = mainPart.AddHyperlinkRelationship(uri, true);
        string relationshipId = rel.Id;
        Paragraph newParagraph = new Paragraph(
            new Hyperlink(
                new ProofError() { Type = ProofingErrorValues.GrammarStart },
                new Run(
                    new RunProperties(
                        new RunStyle() { Val = "Hyperlink" }),
                    new Text(urlLabel)
                )) { History = OnOffValue.FromBoolean(true), Id = relationshipId });
 
        Paragraph p = mainPart.Document.Body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().Last();
        mainPart.Document.Body.InsertAfter<Paragraph>(newParagraph, p);
        mainPart.Document.Save();
    }
 

       wdPackage.Close();
}