Quantcast
Channel: Open XML Format SDK forum
Viewing all articles
Browse latest Browse all 1288

Bookmark whole text between HEADINGS

$
0
0

See below code, which will create bookmark where style is HEADING1. How can we modify this so that text between HEADING1 and next HEADING1 element gets selected under BOOKMARK1.

So Bookmark should include text starting from HEADING1... and should end before HEADING2 starts

  using (var doc = WordprocessingDocument.Open(@"D:\DocFiles\Scan.docx", true))
                {
                    paragraphs = doc.MainDocumentPart.Document.Body
                                    .OfType<Paragraph>().ToList();
                    int bookmarkId = 0;
                    // MyDocuments.Body is a WordProcessDocument.MainDocumentPart.Document.Body
                    foreach (Paragraph para in paragraphs.ToList())
                    {
                        // 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 ="BookmarkbyLokesh" + bookmarkId, Id = bookmarkId.ToString() };
                    BookmarkEnd bme = new BookmarkEnd() { Id = bookmarkId.ToString() };++bookmarkId;

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

                    // 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

                }
                doc.Save();
                doc.Close();


Viewing all articles
Browse latest Browse all 1288

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>