locked
Open XML document unreadable after adding footer RRS feed

  • Question

  • User-1156020352 posted

    I am trying to add footer in a word document by using the below code. The file is getting generated, but when I try to open the file it is showing the message that the document is unreadable. I don't know what I am doing wrong here.

    WordprocessingDocument doc;
        Body docBody;
        public void Insert()
        {
            doc = WordprocessingDocument.Create(@"d:\report1.docx", WordprocessingDocumentType.Document);
            docBody = new Body();
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            mainPart.Document.Body = docBody;
            ApplyFooter();
            doc.Save();
    
        }
    
    
        public void ApplyFooter()
        {
            // Get the main document part.
            MainDocumentPart mainDocPart = doc.MainDocumentPart;
    
            FooterPart footerPart1 = mainDocPart.AddNewPart<FooterPart>("r98");
    
    
    
            Footer footer1 = new Footer();
    
            Paragraph paragraph1 = new Paragraph() { };
    
    
    
            Run run1 = new Run();
            Text text1 = new Text();
            text1.Text = "Footer stuff";
    
            run1.Append(text1);
    
            paragraph1.Append(run1);
    
    
            footer1.Append(paragraph1);
    
            footerPart1.Footer = footer1;
    
    
    
            SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants<SectionProperties>().FirstOrDefault();
            if (sectionProperties1 == null)
            {
                sectionProperties1 = new SectionProperties() { };
                mainDocPart.Document.Body.Append(sectionProperties1);
            }
            FooterReference footerReference1 = new FooterReference() { Type = DocumentFormat.OpenXml.Wordprocessing.HeaderFooterValues.Default, Id = "r98" };
    
    
            sectionProperties1.InsertAt(footerReference1, 0);
    
        }

    Monday, July 22, 2019 12:29 PM

All replies

  • User-1174608757 posted

    Hi Vishwajeet singh,

    According to your description,I notice that you haven't added doc.close() in the method.So I suggest that you could write code as below:

    public void Insert()
        {
            doc = WordprocessingDocument.Create(@"d:\report1.docx", WordprocessingDocumentType.Document);
            docBody = new Body();
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            mainPart.Document.Body = docBody;
            ApplyFooter();
            doc.Close();
        }
    

    Best Regards

    Wei

    Tuesday, July 23, 2019 2:43 AM