如何使用openxml在word中添加链接到标题的超链接

How to add hyperlink that links to heading in word with openxml

我正在尝试将 link 的 hyperlink 添加到同一个 word 文档中的标题。

到目前为止,这是我的代码:

  1. 首先我添加了hyperlink

    Paragraph p = new Paragraph();
    Hyperlink h = new Hyperlink(){ Anchor = new StringValue("_Link") };
    Run r = new Run();
    RunProperties rp = new RunProperties(){ Val = "Hyperlink" };
    Text t = new Text("Click here");
    
    r.Append(rp);
    r.Append(t);
    p.Append(r);
    body.Append(p);
    
  2. 然后我添加标题(带有必要的书签)

    Paragraph p = new Paragraph();
    Run r = new Run(new Text("My Heading"));
    ParagraphProperties pp = new ParagraphProperties();
    ParagraphStyleId psi = new ParagraphStyleId(){ Val = new StringValue("Heading1") };
    
    p.Append(r);
    p.Append(pp);
    p.Append(psi);
    p.Append(new BookmarkStart() { Name = new StringValue("_Link") };
    p.Append(new BookmarkEnd());
    body.Append(p);
    

我不明白我错过了什么。我在 hyperlink 中设置了锚点,它应该 link 到具有相同名称的书签的标题。 (锚点来自 hyperlink == 名称来自标题中的书签)。

或者我是否需要将 HyperLinkRelationship 添加到 MainDocumentPart.HyperlinkRelationship,就像我想将带有 URI 的 hyperlink 添加到网站时必须做的那样?

您正在将 header 作为段落添加到 body,您需要创建 header 部分 -

HeaderPart headerPart = mainDocumentPart.AddNewPart<HeaderPart>();

string headerPartId = mainDocumentPart.GetIdOfPart(headerPart);

GenerateHeaderPartContent(headerPart);

以及 GenerateHeaderPartContent

的代码
 private void GeneratePartContent(HeaderPart part)
        {
            Header header1 = new Header(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "w14 w15 wp14" }  };
            header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            header1.AddNamespaceDeclaration("w15", "http://schemas.microsoft.com/office/word/2012/wordml");
            header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

            Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "00225DC9", RsidRunAdditionDefault = "00225DC9" };

            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "Header" };

            paragraphProperties1.Append(paragraphStyleId1);
            BookmarkStart bookmarkStart1 = new BookmarkStart(){ Name = "HeadingBookmark", Id = "1" };

            Run run1 = new Run();
            Text text1 = new Text();
            text1.Text = "Test";

            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(bookmarkStart1);
            paragraph1.Append(run1);
            BookmarkEnd bookmarkEnd1 = new BookmarkEnd(){ Id = "1" };


            header1.Append(paragraph1);
            header1.Append(bookmarkEnd1);


            part.Header = header1;
        }

header 部分准备就绪后,将其添加到您的文档部分属性 -

HeaderReference headerReference1 = new HeaderReference(){ Type = HeaderFooterValues.Default, Id = headerPartId  };

也是一个很好的检查参考 - https://msdn.microsoft.com/en-us/library/office/cc546917.aspx

DocIO 是一个 .NET 库,可以读取、写入、修改和呈现 Microsoft Word 文档。使用 DocIO,您可以非常轻松地添加书签和超链接。您不必担心超链接的位置(在页眉或页脚或文档正文中)并决定在何处添加引用。

如果您符合条件,可通过 community license program 免费获得整套控件(也可用于商业应用程序)。社区许可证是没有限制或水印的完整产品。

步骤 1:创建控制台应用程序
步骤 2:添加对这 3 个程序集的引用(Syncfusion.DocIO.Base、Syncfusion.Compression.Base 和 Syncfusion.OfficeChart.Base)。您还可以通过 NuGet
添加这些引用 第 3 步:复制并粘贴以下打开现有 Word 文档的代码片段,替换内容并将其另存为 Word 文档。

using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
namespace DocIO_HyperlinkinkToBookmark
{
   class Program
   {
       static void Main(string[] args)
       {
           using (WordDocument document = new WordDocument())
           {
               document.EnsureMinimal();
               IWSection section = document.LastSection;
               IWParagraph paragraph = document.LastParagraph;
               //add text enclosed by BookmarkStart and BookmarkEnd into a paragraph
               paragraph.AppendBookmarkStart("Title1Mark");
               paragraph.AppendText("Title paragraph");
               paragraph.AppendBookmarkEnd("Title1Mark");
               //Add few paragraph of textual data
               for (int i = 0; i < 10; i++)
                   section.AddParagraph().AppendText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
               paragraph = section.AddParagraph();
               //Add a hyperlink with the specified display text and targets to Bookmark named "Title1Mark"
               paragraph.AppendHyperlink("Title1Mark", "Link to Title", HyperlinkType.Bookmark);
               document.Save("output.docx", FormatType.Docx);
           }
       }
    }
}

有关 DocIO 的更多信息,请参阅我们的 help documentation

注意:我为 Syncfusion 工作

For open XML (snippet)

        // Your new paragraph with the hyperlink
        Paragraph hyperlinkParagraph = new Paragraph();

        // Run for the hyperlink
        Run hyperlinkRun = new Run();

        // Styling for the hyperlink
        RunProperties runPropertiesHyperLink = new RunProperties(
            new RunStyle { Val = "Hyperlink", },
            new Underline { Val = UnderlineValues.Single },
            new Color { ThemeColor = ThemeColorValues.Hyperlink });

        // Actual hyperlink
        Hyperlink xmlHyperLink = new Hyperlink()
        {
            Anchor = "https://whosebug.com",
            DocLocation = "https://whosebug.com"
        };
        // Text that you see to click on
        Text hyperLinkText = new Text("Click for going to Whosebug!");

        // Apply the styling in this order to the run
        hyperlinkRun.Append(runPropertiesHyperLink);
        hyperlinkRun.Append(hyperLinkText);
        // Now add the run to the hyperlink
        xmlHyperLink.Append(hyperlinkRun);
        // Add the hyperlink to the paragraph
        hyperlinkParagraph.Append(xmlHyperLink);

        // Add paragraph to the body
        _mainBody.Append(hyperlinkParagraph );