Determining Paragraph Indexes

Home Forums Open-Xml-PowerTools Determining Paragraph Indexes

This topic contains 1 reply, has 2 voices, and was last updated by  Eric White 8 years, 4 months ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #3600

    BlueEyedBehemoth
    Participant

    Hey Eric,

    I’m having an issue merging complex documents with headers at specific locations.

    Here’s an example:

    var letterhead = @"C:\Users\dheale\Desktop\Word Docs\TESTING\StandardLetterhead.DOCX";
    var blackrule = @"C:\Users\dheale\Desktop\Word Docs\TESTING\NJBlackrule.DOCX";
    var asb = @"C:\Users\dheale\Desktop\Word Docs\TESTING\asb.DOCX";
    var outDoc = @"C:\Users\dheale\Desktop\Word Docs\TESTING\out.DOCX";
    
    var sources = new List<Source>
    {
        new Source(new WmlDocument(asb), 0, 80, false),
        new Source(new WmlDocument(letterhead), true),
        new Source(new WmlDocument(asb), 80,120, false),
        new Source(new WmlDocument(blackrule), true),
        new Source(new WmlDocument(asb), 120, false),
        new Source(new WmlDocument(letterhead), true)
    };
    
    var doc = DocumentBuilder.BuildDocument(sources);

    My issue is trying to figure out what the paragraph index is. The original document has tags to identify where the template should be placed.

    Currently to get the ID I’m doing the following:

    var ParagraphIndex = wordDoc.MainDocumentPart.Document.Body.ChildElements.Where(w => w.XmlQualifiedName.Name == "p").ToList().FindIndex(f => f.InnerXml.Contains(templateTag));

    However, the longer the document, the more off this index is.

    Is there a better and more accurate way of getting the indexes of the paragraphs?

    Thanks

    #3665

    Eric White
    Keymaster

    Hi,

    If you look at line 431 in DocumentBuilder.cs, you can see where it selects the content to be included in a source document:

        List<XElement> contents = doc.MainDocumentPart.GetXDocument()
            .Root
            .Element(W.body)
            .Elements()
            .Skip(source.Start)
            .Take(source.Count)
            .ToList();

    If you are not seeing what you want in the merged document, you can look at what is selected in the above statement, see where the discrepancy is. You can calculate the Start and Count such that this statement will return the correct content.

    Looking at your code, nothing stands out as incorrect. Mainly, when I code for this scenario, I actually count elements in the list, rather than using FindIndex, but it seems to me that FindIndex would work just as well.

    My recommendation is to look at the results of the above query, and see why you are not getting the content you want to get.

    Let me know how I can help further…

    Cheers, Eric

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.