簡體   English   中英

如何使用OpenXml將新書簽附加到Word 2010中的現有段落?

[英]How to attach a new bookmark to an existing paragraph in word 2010 using OpenXml?

在Word文檔中,我要為樣式為“標題1”的所有段落設置書簽。

如何使用OpenXml在現有段落中插入新書簽?

為此,您必須:

  1. 查找所有段落
  2. 使用Heading1檢查該段落是否為標題(您必須檢查是否存在paragraphStyleId()在ParagraphProperties(...)內部
  3. 如果它是具有Heading1樣式的段落,請插入書簽。

您應該可以使用以下代碼來執行此操作

        int bookmarkId = 0;
        // MyDocuments.Body is a WordProcessDocument.MainDocumentPart.Document.Body
        foreach(Paragraph para in MyDocuments.Body.Descendants<Paragraph>())
        {
            // if the paragraph has no properties or has properties but no pStyle, it's not a "Heading1"
            ParagraphProperties pPr = para.GetFirstChild<ParagraphProperties>();
            if (pPr == null || pPr.GetFirstChild<ParagraphStyleId>() == null) continue;
            // if the value of the pStyle is not Heading1 => skip the paragraph
            if (pPr.GetFirstChild<ParagraphStyleId>().Val != "Heading1") continue;

            // it's a paragraph with Heading1 style, insert the bookmark

            // the bookmark must have a start and an end
            // the bookmarkstart/end share the same id
            BookmarkStart bms = new BookmarkStart() { Name = "yourbookmarkname", Id = bookmarkId.ToString() };
            BookmarkEnd bme = new BookmarkEnd() { Id = bookmarkId.ToString() };
            ++bookmarkId;

            // Insertion of bookmarkstart after the paragraphProperties
            pPr.InsertAfterSelf(bms);

            // The bookmarkend can be inserted after the bookmarkstart or after the object the bookmark must surrounding
            // here we will insert it after bms. If you want to surround an object, find the object within the paragraph and insert it after
            bms.InsertAfterSelf(bme);

有關Bookmark類的更多信息,請參見: https : //msdn.microsoft.com/zh-cn/library/documentformat.openxml.wordprocessing.bookmarkstart(v=office.14).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM