Search code examples
c#openxml

Link to another file


I'm generating a word document by using open-xml.

There i show names of image files i.e. c:\config\1.jpg c:\config\2.jpg

On-click on those names (cntl+click) those file should be opened. But it doesnt go to the file rather than an anchor to top of the word doc.

I used hyperlink as below

Paragraph paraSummary = body.AppendChild(new Paragraph());
Run runSummary = paraSummary.AppendChild(new Run());
runSummary.AppendChild(new Break());
Hyperlink hl = new Hyperlink(new Run(new Text(item.ToString())))
{
 DocLocation = rootPath1 + "\\" + item.ToString()
};
runSummary.AppendChild(hl);

mainPart.Document.Append(body);
mainPart.Document.Save();

and the xml of generated file is :

-<w:hyperlink w:docLocation="c:\\config\\1.jpg">-<w:r><w:t>1.jpg</w:t></w:r></w:hyperlink>

is there any other solution other than 'Hyperlinks' or anything that i have missed in above code.


Solution

  • According to the Open XML spec. http://officeopenxml.com/WPhyperlink.php docLocation is for external links.

    For All types of hyperlinks we have to create a relationship. for example

    In your case TargetMode can't be external

    In Open XML SDK you can implement this as below code sample

    Hyperlink hl =
    new Hyperlink(new Run(new Text("Link1")))
    {
        Id = "L1"
    };
    
    runSummary.AppendChild(hl);
    
    mainPart.Document.Append(body);
    mainPart.AddHyperlinkRelationship(new Uri("file:\\C:\\config\\image.jpg"), false, "L1");
    

    in AddHyperlinkRelationship method false means that this is not external link (which is for internal link)