none
Program creates the document but generates an error. Is there a way to resolve the error or identify what it stems from? System.InvalidOperationException: Cannot insert the OpenXmlElement "newChild" because it is part of a tree. RRS feed

  • Question

  • Hi All,

    I had been trying to find a way to add a header to my document that worked and seemed simple enough for me.  I found a solution and tried to modifiy it to work with my program.  I created a smaller test version in order to attempt determining how well it worked.  After testing, it generated an error and crashed, however it still created the word document the way I desired (basically a document with a header and body text).  I attempted adding try/catches but removed them as you'll see below because it would still crash and say my exception message variables were null unless I did not try to extract the message from the exception variable.  I am using Visual Web Developer 2013 and OpenXML 2.5.  Any help is appreciated, I've only been using the OpenXML for about 2 weeks.

    Thank you,

    Mitch

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    namespace HASPOnline
    {
        public class TestDoc2
        {
            public TestDoc2()
            {
                    string documentPath = @"C:\Users\me\Desktop\HeaderFooterDocument.docx";
                    using (WordprocessingDocument package = WordprocessingDocument.Create(documentPath, WordprocessingDocumentType.Document))
                    {
                            AddParts(package);
                            MainDocumentPart mainPart = package.MainDocumentPart;
                            Body body = package.MainDocumentPart.Document.Body;
                            Paragraph paraDocType = body.AppendChild(new Paragraph());
                            //Create run thats hold text that will be added to the paragraph
                            Run runDocHeader = paraDocType.AppendChild(new Run());
                            RunProperties rpDocHdr = new RunProperties();
                            rpDocHdr.Append(new Bold());
                            FontSize fs = new FontSize();
                            fs.Val = new StringValue("40");
                            rpDocHdr.Append(fs);
                            runDocHeader.AppendChild<RunProperties>(rpDocHdr);
                            //Add text to the run
                            runDocHeader.AppendChild(new Text("Health and Safety Plan"));
                            //Title Area
                            Paragraph paraHaspTitle = body.AppendChild(new Paragraph());
                            Run runTitle = paraHaspTitle.AppendChild(new Run());
                            RunProperties runproperties = runTitle.AppendChild(new RunProperties(new Bold()));
                            runTitle.AppendChild(new CarriageReturn());//Drop down a line
                            runTitle.AppendChild(new Bold());//Add bold to text
                            runTitle.AppendChild(new Text("Title: ") { Space = SpaceProcessingModeValues.Preserve });
                            //Title text
                            Run runTitleActual = paraHaspTitle.AppendChild(new Run());
                            runTitleActual.AppendChild(new Text("Will hold string variable for title here."));
                            //add body with more content back to document
                            mainPart.Document.Append(body);
                    }
            }
            private static void AddParts(WordprocessingDocument parent)
            {
                string headerText = "HASP#:                                                                Expiration Date:";
                    var mainDocumentPart = parent.AddMainDocumentPart();
                    GenerateMainDocumentPart().Save(mainDocumentPart);
                    var documentSettingsPart = mainDocumentPart.AddNewPart<DocumentSettingsPart>("rId1");
                    GenerateDocumentSettingsPart().Save(documentSettingsPart);
                    var firstPageHeaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId2");
                    GeneratePageHeaderPart(headerText).Save(firstPageHeaderPart);
                    var evenPageHeaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId4");
                    GeneratePageHeaderPart(headerText).Save(evenPageHeaderPart);
                    var oddPageheaderPart = mainDocumentPart.AddNewPart<HeaderPart>("rId6");
                    GeneratePageHeaderPart(headerText).Save(oddPageheaderPart);
            }
            private static Document GenerateMainDocumentPart()
            {
                var element =
                    new Document(
                        new Body(
                            new SectionProperties(
                                new HeaderReference()
                                {
                                    Type = HeaderFooterValues.First,
                                    Id = "rId2"
                                },
                                new HeaderReference()
                                {
                                    Type = HeaderFooterValues.Even,
                                    Id = "rId4"
                                },
                                new HeaderReference()
                                {
                                    Type = HeaderFooterValues.Default,
                                    Id = "rId6"
                                },
                                new PageMargin()
                                {
                                    Top = 1440,
                                    Right = (UInt32Value)1440UL,
                                    Bottom = 1440,
                                    Left = (UInt32Value)1440UL,
                                    Header = (UInt32Value)720UL,
                                    Footer = (UInt32Value)720UL,
                                    Gutter = (UInt32Value)0UL
                                },
                                new TitlePage()
                            )));
                return element;
            }
            private static Header GeneratePageHeaderPart(string HeaderText)
            {
                var element =
                    new Header(
                        new Paragraph(
                            new ParagraphProperties(
                                new ParagraphStyleId() { Val = "Header" }),
                            new Run(
                                new Text(HeaderText))
                        ));
                return element;
            }
            private static Settings GenerateDocumentSettingsPart()
            {
                var element =
                    new Settings(new EvenAndOddHeaders());
                return element;
            }
        }
    }


    • Edited by mjbz Thursday, March 20, 2014 3:55 PM spelling error
    Thursday, March 20, 2014 3:54 PM

Answers

  • Hi,

    Welcome to MSDN forum.

    I tried to run the code you provided and got an issue as you mentioned while executing the code below:

    mainPart.Document.Append(body);

    While creating a new Word document, the body part is existing and we can’t insert another body part into a document.

    So appending the body would cause an issue.

    Every element you appended to body would be saved at last.

    What you need to do is to delete this code.

    After that, the sample works fine for me and I would get a new document as below:

    Hope this helps.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by mjbz Friday, March 21, 2014 1:31 PM
    Friday, March 21, 2014 7:33 AM
    Moderator

All replies

  • Hi,

    Welcome to MSDN forum.

    I tried to run the code you provided and got an issue as you mentioned while executing the code below:

    mainPart.Document.Append(body);

    While creating a new Word document, the body part is existing and we can’t insert another body part into a document.

    So appending the body would cause an issue.

    Every element you appended to body would be saved at last.

    What you need to do is to delete this code.

    After that, the sample works fine for me and I would get a new document as below:

    Hope this helps.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by mjbz Friday, March 21, 2014 1:31 PM
    Friday, March 21, 2014 7:33 AM
    Moderator
  • Thank you.  Removing that line worked well.  I guess since the body is already added to the document in the method "GenerateMainDocumentPart()",  adding it a second time would cause some conflict.  I appreciate your assistance.

    -Mitch

    Friday, March 21, 2014 1:30 PM