Insert Table of Contents TOC Field in Particular Page of Word Document | C# .NET

Hi hafeez,

iam sending toc code which iam working and toc heading code also please see it and above documents which i already send to you please check with that documents we have some security issues for other documents to send to you …toc test.zip (1.1 KB)

@awais.hafeez,
is that possible to use multiple paragraph formats to a single builder, if possible please tell me how to switch between paragraph formats. here I am trying to create toc lot lof with the same builder but with different font parameters. i need to know is that possible or not if not suggest any other way

@k.sukumar,

The problem occurs because of applying “TOC Heading Centered” style to the TOC title paragraph. When you apply this style, the entry becomes visible in Table of Contents too with font formatting applied. This is expected behavior. But you can workaround this by manually applying the font formatting to title paragraph and this will avoid the appearance of title in TOC altogether. Please check the following sample code:

Document doc = new Document(@"C:\Temp\TOC\\2.3 Introduction KY.doc");

Node[] runs = doc.GetChildNodes(NodeType.Run, true).ToArray();
for (int i = 0; i < runs.Length; i++)
{
    Run run = (Run)runs[i];
    int length = run.Text.Length;

    Run currentNode = run;
    for (int x = 1; x < length; x++)
    {
        currentNode = SplitRun(currentNode, 1);
    }
}

DocumentBuilder builder = new DocumentBuilder(doc);

NodeCollection smallRuns = doc.GetChildNodes(NodeType.Run, true);
LayoutCollector collector = new LayoutCollector(doc);

int pageIndex = 2;
foreach (Run run in smallRuns)
{
    if (collector.GetStartPageIndex(run) == pageIndex)
    {
        if (run.GetAncestor(NodeType.Table) == null)
        {
            builder.MoveTo(run.ParentParagraph.PreviousSibling);
            builder.InsertBreak(BreakType.SectionBreakNewPage);

            // Write TOC Title with custom Font formatting

            //// do not use following style to prevent it from appearing in TOC
            // builder.ParagraphFormat.StyleName = "TOC Heading Centered"; 
            // instead manually format the title
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            builder.Font.Name = "Courier";
            builder.Font.Size = 14;
            builder.Writeln("TABLE OF CONTENTS");

            // reset DocumentBuilder's formatting
            builder.Font.ClearFormatting();
            builder.ParagraphFormat.ClearFormatting();

            // Insert TOC
            builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
            builder.Writeln();
            builder.InsertBreak(BreakType.SectionBreakNewPage);
            break;
        }
    }
}

doc.UpdateFields();

doc.Save(@"C:\Temp\\TOC\\21.10.docx");

Attachment: source and output docx files.zip (2.2 MB)

Thank you @hafeez for your help…

i had another issue that i want to add section break for existing toc like i want to add section after table of contents and after that list of tables will be created at that time also i want to add section break . means after toc section break and after list of tables section break and after list of figures section breaks should be added can you help me with this. i have attached the file
2.3 Introduction to Quality Overall Summary.zip (90.9 KB)

@k.sukumar You can use code like the following to insert section break after TOC field:

Document doc = new Document(@"C:\Temp\in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);

NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);
foreach (FieldStart start in fieldStarts)
{
    if (start.FieldType == FieldType.FieldTOC)
    {
        Field toc = start.GetField();
        Paragraph tocEnd = (Paragraph)toc.End.GetAncestor(NodeType.Paragraph);

        builder.MoveTo(tocEnd);
        builder.InsertBreak(BreakType.SectionBreakNewPage);
    }
}

doc.Save(@"C:\temp\out.docx");

Thank you alexey,

iam facing issue when i created toc , lot, and lof i have attached the document … in that when i created toc iam getting list of tables two times how to remove that can you help me with this.

iam actually removing the already toc and adding new toc but when i run project the breakpoint comming to remove filed line but it is not removing . iahve attached the files with pictures and documentstoc issue.zip (181.0 KB)

List<Node> listFieldTOC = TempDoc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldTOC).ToList();
                //Below code for checking toc/LOT/LOF for the file having below 5 pages excluding toc/lot/lof
                if (pagecount >= 5 && listFieldTOC.Count > 0)
                {
                    string Tempfilename = rObj.DestFilePath;
                    Tempfilename = Tempfilename.Replace(rObj.File_Name, "Temp_" + rObj.File_Name);
                    List<Node> SectionBreakslst = TempDoc.GetChildNodes(NodeType.Paragraph, true).Where(x => x.Range.Text.Contains(ControlChar.SectionBreak)).ToList();
                    foreach (Paragraph pr in SectionBreakslst)
                    {
                        Paragraph prbreak = pr;
                        Paragraph prcl = null;
                        if (pr.PreviousSibling != null && pr.PreviousSibling.NodeType == NodeType.Paragraph)
                        {
                            prcl = (Paragraph)prbreak.PreviousSibling;
                        }
                        if (prcl != null && !prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC ")))
                        {
                            if (prcl.IsEndOfSection)
                            {
                                prbreak.ParentSection.Remove();
                            }
                        }
                        if (pr.NextSibling != null && pr.NextSibling.NodeType == NodeType.Paragraph)
                        {
                            prcl = (Paragraph)prbreak.NextSibling;
                        }
                        if (prcl != null && !prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC ")))
                        {
                            if (prcl.IsEndOfSection)
                            {
                                prbreak.ParentSection.Remove();
                            }
                        }
                    }
                    foreach (FieldStart start in TempDoc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldTOC))
                    {
                        if (start.ParentParagraph.PreviousSibling != null && start.ParentParagraph.PreviousSibling.NodeType == NodeType.Paragraph)
                        {
                            Paragraph pr1 = (Paragraph)start.ParentParagraph.PreviousSibling;
                            if (pr1 != null && (pr1.Range.Text.Trim().ToUpper().Contains("TABLE OF CONTENTS") || pr1.Range.Text.Trim().ToUpper().Contains("LIST OF TABLES") || pr1.Range.Text.Trim().ToUpper().Contains("LIST OF FIGURES")))
                                pr1.Remove();
                        }
                        start.GetField().Remove();
                    }
                    Paragraph prB = new Paragraph(TempDoc);
                    List<Node> paragraphs = TempDoc.GetChildNodes(NodeType.Paragraph, true).Where(x => !((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC "))).ToList();
                    foreach (Paragraph pr in paragraphs)
                    {
                        if ((pr.Range.Text.Contains(ControlChar.SectionBreak) && pr.IsEndOfSection) && prB != pr)
                            pr.ParentSection.Remove();
                        if (pr.NextSibling != null && pr.NextSibling.NodeType == NodeType.Paragraph && pr.NextSibling.Range.Text.Contains(ControlChar.SectionBreak))
                        {
                            prB = (Paragraph)pr.NextSibling;
                            if (prB.IsEndOfSection)
                                prB.ParentSection.Remove();
                        }
                        pr.Remove();
                    }

Hi @awais.hafeez
can you help me for above issue mention about list of tables

@k.sukumar Unfortunately your requirements is not quite clear. Could you please attach your input, current output and expected output create in MS Word along with code that produces the output document? We will check and provide you more information.

Hi alexey i have attached all documents with exact information please click alt+f9 when you open both the documents then you get know that the field codes which are generated for generated both list of tables in table of contents page are different but in i want actual otuput is table of contents and list of and if we have figures then it list of figures should be there as mentioned in attached fileCapturetoc.PNG (42.7 KB)
Capturetoc2.PNG (40.3 KB)
toc issue.zip (181.0 KB)
i have attached report also in please check that which we are getting in our applicationCapturetoc3.PNG (40.4 KB)

here iam now producing complete toc code which we are working

please dont share to anyone

public void CheckTOCExists(RegOpsQC rObj, Document doc, List<RegOpsQC> chLst)
        {
            rObj.QC_Result = string.Empty;
            rObj.Comments = string.Empty;
            bool flag = false;
            bool TOCPresentBelowpages = false;
            rObj.CHECK_START_TIME = DateTime.Now;
            bool Tocfamily = false;
            bool CheckLOT = false;
            bool CheckLOF = false;
            bool TableFlag = false;
            bool FigureFlag = false;
            chLst = chLst.Where(x => x.Parent_Check_ID == rObj.CheckList_ID).ToList();
            try
            {
                int pagecount = doc.PageCount;
                Document TempDoc = doc.Clone();
                for (int k = 0; k < chLst.Count; k++)
                {
                    chLst[k].Parent_Checklist_ID = rObj.CheckList_ID;
                    chLst[k].JID = rObj.JID;
                    chLst[k].Job_ID = rObj.Job_ID;
                    chLst[k].Folder_Name = rObj.Folder_Name;
                    chLst[k].File_Name = rObj.File_Name;
                    chLst[k].Created_ID = rObj.Created_ID;
                }
                List<Node> listFieldTOC = TempDoc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldTOC).ToList();
                //Below code for checking toc/LOT/LOF for the file having below 5 pages excluding toc/lot/lof
                if (pagecount >= 5 && listFieldTOC.Count > 0)
                {
                    string Tempfilename = rObj.DestFilePath;
                    Tempfilename = Tempfilename.Replace(rObj.File_Name, "Temp_" + rObj.File_Name);
                    List<Node> SectionBreakslst = TempDoc.GetChildNodes(NodeType.Paragraph, true).Where(x => x.Range.Text.Contains(ControlChar.SectionBreak)).ToList();
                    foreach (Paragraph pr in SectionBreakslst)
                    {
                        Paragraph prbreak = pr;
                        Paragraph prcl = null;
                        if (pr.PreviousSibling != null && pr.PreviousSibling.NodeType == NodeType.Paragraph)
                        {
                            prcl = (Paragraph)prbreak.PreviousSibling;
                        }
                        if (prcl != null && !prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC ")))
                        {
                            if (prcl.IsEndOfSection)
                            {
                                prbreak.ParentSection.Remove();
                            }
                        }
                        if (pr.NextSibling != null && pr.NextSibling.NodeType == NodeType.Paragraph)
                        {
                            prcl = (Paragraph)prbreak.NextSibling;
                        }
                        if (prcl != null && !prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC ")))
                        {
                            if (prcl.IsEndOfSection)
                            {
                                prbreak.ParentSection.Remove();
                            }
                        }
                    }
                    foreach (FieldStart start in TempDoc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldTOC))
                    {
                        if (start.ParentParagraph.PreviousSibling != null && start.ParentParagraph.PreviousSibling.NodeType == NodeType.Paragraph)
                        {
                            Paragraph pr1 = (Paragraph)start.ParentParagraph.PreviousSibling;
                            if (pr1 != null && (pr1.Range.Text.Trim().ToUpper().Contains("TABLE OF CONTENTS") || pr1.Range.Text.Trim().ToUpper().Contains("LIST OF TABLES") || pr1.Range.Text.Trim().ToUpper().Contains("LIST OF FIGURES")))
                                pr1.Remove();
                        }
                        start.GetField().Remove();
                    }
                    Paragraph prB = new Paragraph(TempDoc);
                    List<Node> paragraphs = TempDoc.GetChildNodes(NodeType.Paragraph, true).Where(x => !((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC "))).ToList();
                    foreach (Paragraph pr in paragraphs)
                    {
                        if ((pr.Range.Text.Contains(ControlChar.SectionBreak) && pr.IsEndOfSection) && prB != pr)
                            pr.ParentSection.Remove();
                        if (pr.NextSibling != null && pr.NextSibling.NodeType == NodeType.Paragraph && pr.NextSibling.Range.Text.Contains(ControlChar.SectionBreak))
                        {
                            prB = (Paragraph)pr.NextSibling;
                            if (prB.IsEndOfSection)
                                prB.ParentSection.Remove();
                        }
                        pr.Remove();
                    }
                    TempDoc.Save(Tempfilename);
                    TempDoc = new Document(Tempfilename);
                    if (TempDoc.PageCount < 5)
                        TOCPresentBelowpages = true;
                    File.Delete(Tempfilename);
                }
                // Below code for to check TOC/LOT/LOF for below 5 pages file
                if (pagecount < 5 && !TOCPresentBelowpages)
                {
                    flag = true;
                    if (listFieldTOC.Count > 0)
                        TOCPresentBelowpages = true;
                }
                else if (!TOCPresentBelowpages)
                {
                    //Below code for check TOC/LOT/LOF presenct or not
                    List<Node> fieldnodes = doc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldSequence || ((FieldStart)x).FieldType == FieldType.FieldTOC).ToList();
                    foreach (FieldStart nd in fieldnodes)
                    {
                        if (nd.FieldType == FieldType.FieldSequence)
                        {
                            if (nd.ParentNode.GetText().Trim().ToUpper().Contains("SEQ TABLE") && TableFlag != true)
                                TableFlag = true;
                            else if (nd.ParentNode.GetText().Trim().ToUpper().Contains("SEQ FIGURE") && FigureFlag != true)
                                FigureFlag = true;
                        }
                        if (nd.FieldType == FieldType.FieldTOC)
                        {
                            if (!nd.ParentNode.Range.Text.Trim().ToUpper().Contains("\"FIGURE\"") && !nd.ParentNode.Range.Text.Trim().ToUpper().Contains("\"TABLE\""))
                                Tocfamily = true;
                            else if (nd.ParentNode.Range.Text.Trim().ToUpper().Contains("\"TABLE\""))
                                CheckLOT = true;
                            else if (nd.ParentNode.Range.Text.Trim().ToUpper().Contains("\"FIGURE\""))
                                CheckLOF = true;
                        }
                    }
                }
                if (TOCPresentBelowpages == true)
                {
                    rObj.QC_Result = "Failed";
                    rObj.Comments = "TOC/LOT/LOF are present for document with below 5 pages";
                }
                else if (flag == true && TOCPresentBelowpages == false)
                {
                    if (rObj.Check_Type == 1)
                        rObj.QC_Result = "Failed";
                    else
                        rObj.QC_Result = "Passed";
                    rObj.Comments = "TOC,LOT and LOF are not required for document with below 5 pages";
                }
                else if (Tocfamily == true && CheckLOT == true && CheckLOF == true)
                {
                    rObj.QC_Result = "Passed";
                    rObj.Comments = "TOC,LOT and LOF are present for 5 or above 5 pages";
                }
                else if (Tocfamily == false && CheckLOT == false && FigureFlag == true && TableFlag == true && CheckLOF == false)
                {
                    rObj.QC_Result = "Failed";
                    rObj.Comments = "TOC,LOT and LOF are not present";
                }
                else if (Tocfamily == false && CheckLOT == false && TableFlag == true && CheckLOF == true)
                {
                    rObj.QC_Result = "Failed";
                    rObj.Comments = "TOC and LOT are not present";
                }
                else if (Tocfamily == false && CheckLOT == true && CheckLOF == false && FigureFlag == true)
                {
                    rObj.QC_Result = "Failed";
                    rObj.Comments = "TOC and LOF are not present";
                }
                else if (Tocfamily == true && CheckLOT == false && FigureFlag == true && TableFlag == true && CheckLOF == false)
                {
                    rObj.QC_Result = "Failed";
                    rObj.Comments = "LOT and LOF are not present";
                }
                else if (Tocfamily == true && CheckLOT == true && FigureFlag == false && CheckLOF == false)
                {
                    if (rObj.Check_Type == 1)
                        rObj.QC_Result = "Failed";
                    else
                        rObj.QC_Result = "Passed";
                    rObj.Comments = "TOC and LOT are present";
                }
                else if (Tocfamily == true && CheckLOT == false && TableFlag == false && CheckLOF == true)
                {
                    if (rObj.Check_Type == 1)
                        rObj.QC_Result = "Failed";
                    else
                        rObj.QC_Result = "Passed";
                    rObj.Comments = "TOC and LOF are present";
                }
                else if (Tocfamily == true && CheckLOT == false && TableFlag == false && CheckLOF == false && FigureFlag == false)
                {
                    if (rObj.Check_Type == 1)
                        rObj.QC_Result = "Failed";
                    else
                        rObj.QC_Result = "Passed";
                    rObj.Comments = "TOC present";
                }
                else if (Tocfamily == false)
                {
                    rObj.QC_Result = "Failed";
                    rObj.Comments = "TOC not present";
                }
                else if (CheckLOT == false && TableFlag == true)
                {
                    rObj.QC_Result = "Failed";
                    rObj.Comments = "LOT not present";
                }
                else if (CheckLOF == false && FigureFlag == true)
                {
                    rObj.QC_Result = "Failed";
                    rObj.Comments = "LOF not present";
                }
                else
                {
                    if (rObj.Check_Type == 1)
                        rObj.QC_Result = "Failed";
                    else
                        rObj.QC_Result = "Passed";
                    rObj.Comments = "This Check is passed";
                }
                if (rObj.Comments != "TOC,LOT and LOF are not required for document with below 5 pages" && rObj.Comments != "TOC/LOT/LOF are present for document with below 5 pages")
                {
                    //Below code to check predict styles
                    bool Predictflag = false;
                    foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldTOC))
                    {
                        Predictflag = false;
                        RegOpsQC Predictstyles = new RegOpsQC();
                        RegOpsQC CheckList = new RegOpsQC();
                        List<Node> FontsLst = new List<Node>();
                        List<Node> ParaList = new List<Node>();
                        Style ExistingStyle = null;
                        if (start.ParentParagraph.PreviousSibling != null && start.ParentParagraph.PreviousSibling.NodeType == NodeType.Paragraph)
                        {
                            Paragraph pr = (Paragraph)start.ParentParagraph.PreviousSibling;
                            if (chLst.Count > 0 && pr != null && (pr.Range.Text.Trim().ToUpper().Contains("TABLE OF CONTENTS") || pr.Range.Text.Trim().ToUpper().Contains("LIST OF TABLES") || pr.Range.Text.Trim().ToUpper().Contains("LIST OF FIGURES")))
                            {
                                if (pr.Range.Text.Trim().ToUpper().Contains("TABLE OF CONTENTS"))
                                {
                                    CheckList = chLst.Where(x => x.Check_Name == "\"Table of Contents\" Heading Style").FirstOrDefault();
                                }
                                else if (pr.Range.Text.Trim().ToUpper().Contains("LIST OF TABLES"))
                                {
                                    CheckList = chLst.Where(x => x.Check_Name == "\"List of Tables\" Heading Style").FirstOrDefault();
                                }
                                else if (pr.Range.Text.Trim().ToUpper().Contains("LIST OF FIGURES"))
                                {
                                    CheckList = chLst.Where(x => x.Check_Name == "\"List of Figures\" Heading Style").FirstOrDefault();
                                }
                                if (CheckList != null && CheckList.Check_Type == 1)
                                {
                                    //ExistingStyle = doc.Styles.Where(x => ((Style)x).Name.ToUpper() == CheckList.Check_Parameter.ToString().ToUpper() || ((Style)x).StyleIdentifier.ToString().ToUpper() == CheckList.Check_Parameter.ToString().ToUpper()).FirstOrDefault<Style>();
                                    //if (ExistingStyle != null)
                                    //    pr.ParagraphFormat.Style = ExistingStyle;
                                    Predictstyles = new WordParagraphActions().GetPredictstyles(rObj.Created_ID, CheckList.Check_Parameter.ToString());
                                    if (Predictstyles != null)
                                    {
                                        FontsLst = pr.GetChildNodes(NodeType.Run, true).Where(x => ((Run)x).Font.Bold != Convert.ToBoolean(Predictstyles.Fontbold) || ((Run)x).Font.Italic != Convert.ToBoolean(Predictstyles.Fontitalic) || ((Run)x).Font.Size != Convert.ToDouble(Predictstyles.Fontsize) || ((Run)x).Font.Name != Predictstyles.Fontname).ToList();
                                    }
                                    if (FontsLst.Count > 0 || (Predictstyles.Shading != "" && Predictstyles.Shading != null && pr.ParagraphFormat.Shading.BackgroundPatternColor.Name.ToString() != Predictstyles.Shading) || (Predictstyles.Stylename != "" && Predictstyles.Stylename != null && pr.ParagraphFormat.StyleName != Predictstyles.Stylename) || (Predictstyles.Spaceafter != "" && Predictstyles.Spaceafter != null && pr.ParagraphFormat.SpaceAfter != Convert.ToDouble(Predictstyles.Spaceafter)) || (Predictstyles.Spacebefore != "" && Predictstyles.Spacebefore != null && pr.ParagraphFormat.SpaceBefore != Convert.ToDouble(Predictstyles.Spacebefore)) || (Predictstyles.Linespacing != "" && Predictstyles.Linespacing != null && pr.ParagraphFormat.LineSpacing != Convert.ToDouble(Predictstyles.Linespacing)) || (Predictstyles.Alignment != "" && Predictstyles.Alignment != null && pr.ParagraphFormat.Alignment.ToString() != Predictstyles.Alignment))
                                    {
                                        Predictflag = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (Predictflag)
                    {
                        rObj.QC_Result = "Failed";
                        rObj.Comments = "Given styles applied for existing toc, " + rObj.Comments;
                    }
                }
                rObj.CHECK_END_TIME = DateTime.Now;
            }
            catch (Exception ex)
            {
                ErrorLogger.Error("JOB_ID:" + rObj.Job_ID + ", CHECK NAME: " + rObj.Check_Name + "\n" + ex);
                rObj.Job_Status = "Error";
                rObj.QC_Result = "Error";
                rObj.Comments = "Technical error: " + ex.Message;
            }
        }
        private System.Drawing.Color GetSystemDrawingColorFromHexString(string hexString)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(hexString, @"[#]([0-9]|[a-f]|[A-F]){6}\b"))
                throw new ArgumentException();
            int red = int.Parse(hexString.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
            int green = int.Parse(hexString.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
            int blue = int.Parse(hexString.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
            return Color.FromArgb(red, green, blue);
        }
        /// <summary>
        /// Check whether TOC,LOT,LOF and LOA are present for above 5 pages - fix
        /// </summary>
        /// <param name="rObj"></param>
        /// <param name="doc"></param>
        public void FixTOC(RegOpsQC rObj, Document doc, List<RegOpsQC> chLst)
        {
            string res = string.Empty;
            bool Tocfamily = false;
            bool CheckLOT = false;
            bool CheckLOF = false;
            bool TableFlag = false;
            bool FigureFlag = false;
            bool CheckHeading = false;
            bool FixToc = false;
            bool FixLot = false;
            bool FixLof = false;
            string toccolor = string.Empty;
            string Tocstyname = string.Empty;
            string CheckStyles = string.Empty;
            rObj.CHECK_START_TIME = DateTime.Now;
            string Tocposition = string.Empty;
            Style TOCStylename = null;
            Style LOTStylename = null;
            Style LOFStylename = null;
            string TOCFormat = string.Empty;
            string CommonComment = string.Empty;
            string FinalComment = string.Empty;
            bool CheckFix = false;
            bool PredictFlag = false;
            try
            {
                doc = new Document(rObj.DestFilePath);
                chLst = chLst.Where(x => x.Parent_Check_ID == rObj.CheckList_ID).ToList();
                int pagecount = doc.PageCount;
                for (int k = 0; k < chLst.Count; k++)
                {
                    if (chLst[k].Check_Type == 1)
                    {
                        CheckFix = true;
                    }
                }
                if (rObj.Comments.Contains("TOC,LOT and LOF are not required for document with below 5 pages") && pagecount < 5)
                {
                    rObj.QC_Result = "Passed";
                    return;
                }
                //Code for adding predict styles
                if (CheckFix && rObj.Comments.Contains("Given styles applied for existing toc"))
                {
                    foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldTOC))
                    {
                        RegOpsQC Predictstyles = new RegOpsQC();
                        RegOpsQC CheckList = new RegOpsQC();
                        List<Node> FontsLst = new List<Node>();
                        List<Node> FontsBoldLst = new List<Node>();
                        List<Node> FontsSizeLst = new List<Node>();
                        List<Node> FontNamesLst = new List<Node>();
                        List<Node> FontsItalicLst = new List<Node>();
                        Style ExistingStyle = null;
                        bool AddComment = false;
                        string HeadingName = string.Empty;
                        if (start.ParentParagraph.PreviousSibling != null && start.ParentParagraph.PreviousSibling.NodeType == NodeType.Paragraph)
                        {
                            Paragraph pr = (Paragraph)start.ParentParagraph.PreviousSibling;
                            if (chLst.Count > 0 && pr != null && (pr.Range.Text.Trim().ToUpper().Contains("TABLE OF CONTENTS") || pr.Range.Text.Trim().ToUpper().Contains("LIST OF TABLES") || pr.Range.Text.Trim().ToUpper().Contains("LIST OF FIGURES")))
                            {
                                if (pr.Range.Text.Trim().ToUpper().Contains("TABLE OF CONTENTS"))
                                {
                                    CheckList = chLst.Where(x => x.Check_Name == "\"Table of Contents\" Heading Style").FirstOrDefault();
                                    if (CheckList != null && CheckList.Check_Type == 1)
                                    {
                                        HeadingName = "TOC Heading:";
                                    }
                                }
                                else if (pr.Range.Text.Trim().ToUpper().Contains("LIST OF TABLES"))
                                {
                                    CheckList = chLst.Where(x => x.Check_Name == "\"List of Tables\" Heading Style").FirstOrDefault();
                                    if (CheckList != null && CheckList.Check_Type == 1)
                                    {
                                        HeadingName = " LOT Heading:";
                                    }
                                }
                                else if (pr.Range.Text.Trim().ToUpper().Contains("LIST OF FIGURES"))
                                {
                                    CheckList = chLst.Where(x => x.Check_Name == "\"List of Figures\" Heading Style").FirstOrDefault();
                                    if (CheckList != null && CheckList.Check_Type == 1)
                                    {
                                        HeadingName = " LOF Heading:";
                                    }
                                }
                                if (CheckList != null && CheckList.Check_Type == 1)
                                {
                                    ExistingStyle = doc.Styles.Where(x => ((Style)x).Name.ToUpper() == CheckList.Check_Parameter.ToString().ToUpper() || ((Style)x).StyleIdentifier.ToString().ToUpper() == CheckList.Check_Parameter.ToString().ToUpper()).FirstOrDefault<Style>();
                                    Predictstyles = new WordParagraphActions().GetPredictstyles(rObj.Created_ID, CheckList.Check_Parameter.ToString());
                                    if (Predictstyles != null && ExistingStyle != null)
                                    {
                                        //pr.ParagraphFormat.OutlineLevel = OutlineLevel.Level1;
                                        if (Predictstyles.Fontbold != null && Predictstyles.Fontbold != "")
                                        {
                                            FontsBoldLst = pr.GetChildNodes(NodeType.Run, true).Where(x => ((Run)x).Font.Bold != Convert.ToBoolean(Predictstyles.Fontbold)).ToList();
                                            if (FontsBoldLst.Count > 0)
                                            {
                                                CommonComment = CommonComment + " Font Bold should be '" + Predictstyles.Fontbold + "',";
                                                foreach (Run fnrun in pr.Runs)
                                                {
                                                    PredictFlag = true;
                                                    AddComment = true;
                                                    fnrun.Font.Bold = Convert.ToBoolean(Predictstyles.Fontbold);
                                                }
                                            }
                                        }
                                        if (Predictstyles.Fontsize != null && Predictstyles.Fontsize != "")
                                        {
                                            FontsSizeLst = pr.GetChildNodes(NodeType.Run, true).Where(x => ((Run)x).Font.Size != Convert.ToDouble(Predictstyles.Fontsize)).ToList();
                                            if (FontsSizeLst.Count > 0)
                                            {
                                                CommonComment = CommonComment + " Font size should be '" + Predictstyles.Fontsize + "',";
                                                foreach (Run fnrun in pr.Runs)
                                                {
                                                    PredictFlag = true;
                                                    AddComment = true;
                                                    fnrun.Font.Size = Convert.ToDouble(Predictstyles.Fontsize);
                                                }
                                            }
                                        }
                                        if (Predictstyles.Fontname != null && Predictstyles.Fontname != "")
                                        {
                                            FontNamesLst = pr.GetChildNodes(NodeType.Run, true).Where(x => ((Run)x).Font.Name != Predictstyles.Fontname).ToList();
                                            if (FontNamesLst.Count > 0)
                                            {
                                                FontNamesLst = FontNamesLst.Where(x => ((Run)x).Font.Name.ToUpper() != "SYMBOL").ToList();
                                            }
                                            if (FontNamesLst.Count > 0)
                                            {
                                                CommonComment = CommonComment + " Font name should be '" + Predictstyles.Fontname + "',";
                                                foreach (Run fnrun in pr.Runs)
                                                {
                                                    if (fnrun.Font.Name.ToUpper() != "SYMBOL")
                                                    {
                                                        PredictFlag = true;
                                                        AddComment = true;
                                                        fnrun.Font.Name = Predictstyles.Fontname;
                                                    }
                                                }
                                            }
                                        }
                                        if (Predictstyles.Fontitalic != null && Predictstyles.Fontitalic != "")
                                        {
                                            FontsItalicLst = pr.GetChildNodes(NodeType.Run, true).Where(x => ((Run)x).Font.Italic != Convert.ToBoolean(Predictstyles.Fontitalic)).ToList();
                                            if (FontsItalicLst.Count > 0)
                                            {
                                                CommonComment = CommonComment + " Font italic should be '" + Predictstyles.Fontitalic + "',";
                                                foreach (Run fnrun in pr.Runs)
                                                {
                                                    PredictFlag = true;
                                                    AddComment = true;
                                                    fnrun.Font.Italic = Convert.ToBoolean(Predictstyles.Fontitalic);
                                                }
                                            }
                                        }
                                        if (Predictstyles.Shading != "" && Predictstyles.Shading != null && pr.ParagraphFormat.Shading.BackgroundPatternColor.Name.ToString() != Predictstyles.Shading)
                                        {
                                            PredictFlag = true;
                                            AddComment = true;
                                            pr.ParagraphFormat.Shading.BackgroundPatternColor = System.Drawing.Color.Empty;
                                            CommonComment = CommonComment + " Shading should be '" + Predictstyles.Shading + "',";
                                        }
                                        if (Predictstyles.Stylename != "" && Predictstyles.Stylename != null && pr.ParagraphFormat.StyleName != Predictstyles.Stylename)
                                        {
                                            PredictFlag = true;
                                            AddComment = true;
                                            pr.ParagraphFormat.StyleName = Predictstyles.Stylename;
                                            CommonComment = CommonComment + " Style name should be '" + Predictstyles.Stylename + "',";
                                        }
                                        if (Predictstyles.Spaceafter != "" && Predictstyles.Spaceafter != null && pr.ParagraphFormat.SpaceAfter != Convert.ToDouble(Predictstyles.Spaceafter))
                                        {
                                            PredictFlag = true;
                                            AddComment = true;
                                            pr.ParagraphFormat.SpaceAfter = Convert.ToDouble(Predictstyles.Spaceafter);
                                            CommonComment = CommonComment + " Space after should be '" + Predictstyles.Spaceafter + "',";
                                        }
                                        if (Predictstyles.Spacebefore != "" && Predictstyles.Spacebefore != null && pr.ParagraphFormat.SpaceBefore != Convert.ToDouble(Predictstyles.Spacebefore))
                                        {
                                            PredictFlag = true;
                                            AddComment = true;
                                            pr.ParagraphFormat.SpaceBefore = Convert.ToDouble(Predictstyles.Spacebefore);
                                            CommonComment = CommonComment + " Space before should be '" + Predictstyles.Spacebefore + "',";
                                        }
                                        if (Predictstyles.Linespacing != "" && Predictstyles.Linespacing != null && pr.ParagraphFormat.LineSpacing != Convert.ToDouble(Predictstyles.Linespacing))
                                        {
                                            PredictFlag = true;
                                            AddComment = true;
                                            pr.ParagraphFormat.LineSpacing = Convert.ToDouble(Predictstyles.Linespacing);
                                            CommonComment = CommonComment + " Line spacing should be '" + Predictstyles.Linespacing + "',";
                                        }
                                        if (Predictstyles.Alignment != "" && Predictstyles.Alignment != null && pr.ParagraphFormat.Alignment.ToString() != Predictstyles.Alignment)
                                        {
                                            PredictFlag = true;
                                            AddComment = true;
                                            if (Predictstyles.Alignment == "Left")
                                                pr.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                                            else if (Predictstyles.Alignment == "Right")
                                                pr.ParagraphFormat.Alignment = ParagraphAlignment.Right;
                                            else
                                                pr.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                                            CommonComment = CommonComment + " Alignment should be '" + Predictstyles.Alignment + "',";
                                        }
                                        CommonComment = CommonComment.TrimEnd(',');
                                        CommonComment = CommonComment + ".";
                                        if (AddComment)
                                        {
                                            FinalComment = FinalComment + HeadingName + CommonComment;
                                            CommonComment = string.Empty;
                                        }
                                        if (ExistingStyle != null && PredictFlag)
                                        {
                                            // pr.ParagraphFormat.Style = ExistingStyle;
                                            foreach (Run run in pr.Runs)
                                            {
                                                run.Font.Bold = ExistingStyle.Font.Bold;
                                                run.Font.Italic = ExistingStyle.Font.Italic;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // Code for removing toc/lot/lof for below 5 pages (Including or excluding toc/lot/lof)
                if (CheckFix && rObj.Comments == "TOC/LOT/LOF are present for document with below 5 pages")
                {
                    List<Node> SectionBreakslst = doc.GetChildNodes(NodeType.Paragraph, true).Where(x => x.Range.Text.Contains(ControlChar.SectionBreak)).ToList();
                    foreach (Paragraph pr in SectionBreakslst)
                    {
                        Paragraph prbreak = pr;
                        Paragraph prcl = null;
                        if (pr.PreviousSibling != null && pr.PreviousSibling.NodeType == NodeType.Paragraph)
                        {
                            prcl = (Paragraph)prbreak.PreviousSibling;
                        }
                        //if (prcl != null && !prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC ")))
                        //{
                        //    if (prcl.IsEndOfSection)
                        //    {
                        //        prbreak.ParentSection.Body.Remove();
                        //    }
                        //}
                        if (pr.NextSibling != null && pr.NextSibling.NodeType == NodeType.Paragraph)
                        {
                            prcl = (Paragraph)prbreak.NextSibling;
                        }
                        //if (prcl != null && !prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || prcl.ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC ")))
                        //{
                        //    if (prcl.IsEndOfSection)
                        //    {
                        //        prbreak.ParentSection.Body.Remove();
                        //    }
                        //}
                    }
                    foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldTOC))
                    {
                        if (start.ParentParagraph.PreviousSibling != null && start.ParentParagraph.PreviousSibling.NodeType == NodeType.Paragraph)
                        {
                            Paragraph pr1 = (Paragraph)start.ParentParagraph.PreviousSibling;
                            start.GetField().Remove();
                            if (pr1 != null && (pr1.Range.Text.Trim().ToUpper().Contains("TABLE OF CONTENTS") || pr1.Range.Text.Trim().ToUpper().Contains("LIST OF TABLES") || pr1.Range.Text.Trim().ToUpper().Contains("LIST OF FIGURES")))
                            {
                                pr1.Remove();
                            }
                        }
                    }
                    Paragraph prB = new Paragraph(doc);
                    List<Node> paragraphs = doc.GetChildNodes(NodeType.Paragraph, true).Where(x => !((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper().Contains("NoTOC") && (((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF FIGURES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "TOC HEADING CENTERED" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "LIST OF TABLES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper() == "TABLE OF FIGURES" || ((Paragraph)x).ParagraphFormat.StyleName.Trim().ToUpper().Contains("TOC "))).ToList();
                    foreach (Paragraph pr in paragraphs)
                    {
                        //if ((pr.Range.Text.Contains(ControlChar.SectionBreak) && pr.IsEndOfSection) && prB != pr)
                        //{                          
                        //    //NodeCollection SectionLst = doc.GetChildNodes(NodeType.Section, true);
                        //    //foreach(Section section in SectionLst)
                        //    //{
                        //    //    section.HeadersFooters.LinkToPrevious(false);
                        //    //}
                        //    Section sct = pr.ParentSection;
                        //    // pr.ParentSection.Remove();
                        //    sct.HeadersFooters.LinkToPrevious(false);
                        //    sct.Body.Remove();
                        //    pr.Remove();

                        //}
                        //if (pr.NextSibling != null && pr.NextSibling.NodeType == NodeType.Paragraph && pr.NextSibling.Range.Text.Contains(ControlChar.SectionBreak))
                        //{
                        //    prB = (Paragraph)pr.NextSibling;
                        //    if (prB.IsEndOfSection)
                        //        prB.ParentSection.Remove();
                        //}
                        if (!pr.Range.Text.Contains("\f"))
                            pr.Remove();
                    }
                    //rObj.QC_Result = "Fixed";
                    rObj.Is_Fixed = 1;
                    rObj.Comments = "TOC/LOT/LOF Removed from the document below 5 pages";
                }
                else
                {
                    //Code for to check toc/lot/lof presence and to check given styles exist or not
                    Style paraStyle = null;
                    StyleCollection stylist = doc.Styles;
                    if (stylist.Where(x => x.Name.ToUpper() == "PARAGRAPH").Count() == 0)
                        paraStyle = stylist.Where(x => x.Name.ToUpper() == "PARAGRAPH").FirstOrDefault();
                    List<Node> TblCaptionFieldseq = doc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldSequence && ((FieldStart)x).ParentParagraph.GetText().Trim().ToUpper().StartsWith("TABLE")).ToList();
                    List<Node> FgrCaptionFieldseq = doc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldSequence && ((FieldStart)x).ParentParagraph.GetText().Trim().ToUpper().StartsWith("FIGURE")).ToList();
                    NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);
                    List<Node> fieldnodes = doc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldSequence || ((FieldStart)x).FieldType == FieldType.FieldTOC).ToList();
                    foreach (FieldStart nd in fieldnodes)
                    {
                        if (nd.FieldType == FieldType.FieldSequence)
                        {
                            if (nd.ParentNode.Range.Text.Trim().ToUpper().Contains("SEQ TABLE") && TableFlag != true)
                                TableFlag = true;
                            else if (nd.ParentNode.Range.Text.Trim().ToUpper().Contains("SEQ FIGURE") && FigureFlag != true)
                                FigureFlag = true;
                        }
                        if (nd.FieldType == FieldType.FieldTOC)
                        {
                            if (!nd.ParentNode.Range.Text.Trim().ToUpper().Contains("\"FIGURE\"") && !nd.ParentNode.Range.Text.Trim().ToUpper().Contains("\"TABLE\""))
                                Tocfamily = true;
                            else if (nd.ParentNode.Range.Text.Trim().ToUpper().Contains("\"TABLE\""))
                                CheckLOT = true;
                            else if (nd.ParentNode.Range.Text.Trim().ToUpper().Contains("\"FIGURE\""))
                                CheckLOF = true;
                        }
                    }
                    for (int k = 0; k < chLst.Count; k++)
                    {
                        chLst[k].Parent_Checklist_ID = rObj.CheckList_ID;
                        chLst[k].JID = rObj.JID;
                        chLst[k].Job_ID = rObj.Job_ID;
                        chLst[k].Folder_Name = rObj.Folder_Name;
                        chLst[k].File_Name = rObj.File_Name;
                        chLst[k].Created_ID = rObj.Created_ID;
                        if (chLst[k].Check_Name == "\"Table of Contents\" Heading Style" && chLst[k].Check_Type == 1)
                        {
                            TOCStylename = doc.Styles.Where(x => ((Style)x).Name.ToUpper() == chLst[k].Check_Parameter.ToString().ToUpper() || ((Style)x).StyleIdentifier.ToString().ToUpper() == chLst[k].Check_Parameter.ToString().ToUpper()).FirstOrDefault<Style>();// ToList<Style>();                                                          
                            if (TOCStylename == null)
                                CheckStyles = CheckStyles + chLst[k].Check_Parameter + ",";
                        }
                        else if (chLst[k].Check_Name == "\"List of Tables\" Heading Style" && chLst[k].Check_Type == 1)
                        {
                            LOTStylename = doc.Styles.Where(x => ((Style)x).Name.ToUpper() == chLst[k].Check_Parameter.ToString().ToUpper() || ((Style)x).StyleIdentifier.ToString().ToUpper() == chLst[k].Check_Parameter.ToString().ToUpper()).FirstOrDefault<Style>();// ToList<Style>();                                                          
                            if (LOTStylename == null)
                                CheckStyles = CheckStyles + chLst[k].Check_Parameter + ",";
                        }
                        else if (chLst[k].Check_Name == "\"List of Figures\" Heading Style" && chLst[k].Check_Type == 1)
                        {
                            LOFStylename = doc.Styles.Where(x => ((Style)x).Name.ToUpper() == chLst[k].Check_Parameter.ToString().ToUpper() || ((Style)x).StyleIdentifier.ToString().ToUpper() == chLst[k].Check_Parameter.ToString().ToUpper()).FirstOrDefault<Style>();// ToList<Style>();                              
                            if (LOFStylename == null)
                                CheckStyles = CheckStyles + chLst[k].Check_Parameter + ",";
                            // List<Style> stere = doc.Styles.Where(x => ((Style)x).Name.ToUpper() == chLst[k].Check_Parameter.ToString().ToUpper() || ((Style)x).StyleIdentifier.ToString().ToUpper() == chLst[k].Check_Parameter.ToString().ToUpper()).ToList();
                        }
                        else if (chLst[k].Check_Name == "TOC starts from")
                            Tocposition = chLst[k].Check_Parameter;
                        else if (chLst[k].Check_Name == "TOC Format")
                            TOCFormat = chLst[k].Check_Parameter;
                    }
                    //code for to add toc/Lot/lof
                    if (!Tocfamily)
                    {
                        //code for to find location to add toc.
                        Node heading = null;
                        DocumentBuilder builder = new DocumentBuilder(doc);
                        if ((CheckLOF || CheckLOT) && TOCStylename != null)
                        {
                            List<Node> Checkfieldsnodes = doc.GetChildNodes(NodeType.Any, true).Where(x => (x.NodeType == NodeType.FieldStart)).ToList();
                            foreach (FieldStart nd in doc.GetChildNodes(NodeType.FieldStart, true).Where(x => ((FieldStart)x).FieldType == FieldType.FieldTOC))
                            {
                                if (nd.ParentNode.PreviousSibling == null || nd.ParentNode.PreviousSibling.PreviousSibling == null)
                                {
                                    Paragraph pr = new Paragraph(doc);
                                    doc.Sections[0].Body.PrependChild(pr);
                                    builder.MoveTo(pr);
                                    break;
                                }
                                else
                                {
                                    heading = nd.ParentNode.PreviousSibling.PreviousSibling;
                                    builder.MoveTo(heading);
                                    break;
                                }
                            }
                        }
                        if (!CheckLOF && !CheckLOT && TOCStylename != null)
                        {
                            if (Tocposition == "Page 1")
                            {
                                CheckHeading = true;
                                Paragraph pr = new Paragraph(doc);
                                doc.Sections[0].Body.PrependChild(pr);
                                builder.MoveTo(pr);
                            }
                            else
                            {
                                foreach (Paragraph pr1 in paragraphs)
                                {
                                    if (pr1.ParagraphFormat.StyleIdentifier == StyleIdentifier.Heading1 || pr1.ParagraphFormat.StyleName.ToUpper() == "HEADING 1 UNNUMBERED" || pr1.ParagraphFormat.StyleName.ToUpper() == "HEADING 1 NOTOC")
                                    {
                                        CheckHeading = true;
                                        if (pr1.PreviousSibling == null)
                                        {
                                            Paragraph pr = new Paragraph(doc);
                                            pr1.ParentSection.Body.PrependChild(pr);
                                            builder.MoveTo(pr);
                                            break;
                                        }
                                        else
                                        {
                                            if (pr1.PreviousSibling.NodeType == NodeType.Table)
                                            {
                                                Table table = (Table)pr1.PreviousSibling;
                                                if (table.NextSibling.ToString(SaveFormat.Text).Trim() != null && table.NextSibling.ToString(SaveFormat.Text).Trim() != "")
                                                {
                                                    Paragraph par = new Paragraph(doc);
                                                    table.ParentNode.InsertAfter(par, table);
                                                    builder.MoveTo(par);
                                                }
                                            }
                                            else
                                            {
                                                heading = pr1.PreviousSibling;
                                                Paragraph par = new Paragraph(doc);
                                                pr1.ParentNode.InsertBefore(par, pr1);                                      
                                                builder.MoveTo(par);                                    
                                         
                                            }
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                            break;
                                        }
                                    }
                                }
                            }
                            if (CheckHeading == false)
                            {
                                Paragraph pr = new Paragraph(doc);
                                doc.Sections[0].Body.PrependChild(pr);
                                builder.MoveTo(pr);
                            }
                        }
                        //Below Code for adding toc/lot/lof
                        if (chLst.Count > 0)
                        {
                            for (int k = 0; k < chLst.Count; k++)
                            {
                                chLst[k].Parent_Checklist_ID = rObj.CheckList_ID;
                                chLst[k].JID = rObj.JID;
                                chLst[k].Job_ID = rObj.Job_ID;
                                chLst[k].Folder_Name = rObj.Folder_Name;
                                chLst[k].File_Name = rObj.File_Name;
                                chLst[k].Created_ID = rObj.Created_ID;
                                if (chLst[k].Check_Name == "\"Table of Contents\" Heading Style" && chLst[k].Check_Type == 1)
                                {
                                    if (TOCStylename != null)
                                    {
                                        //TOCStylename.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;
                                        builder.ParagraphFormat.Style = TOCStylename;
                                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                                        builder.Writeln("TABLE OF CONTENTS");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        if (TOCFormat != null && TOCFormat != "")
                                            builder.InsertTableOfContents(TOCFormat);
                                        else
                                        {
                                            builder.InsertTableOfContents("TOC \\o \"1 - 3\" \\h \\z \\u");
                                            // builder.InsertTableOfContents("TOC \\H \\Z \\T \"LIST OF FIGURES, 1, LIST OF TABLES, 1, LIST OF APPENDICES, 1, HEADING 1, 1, HEADING 1 UNNUMBERED, 1, HEADING 2, 2, HEADING 2 UNNUMBERED, 2, HEADING 3, 3, HEADING 3 UNNUMBERED, 3, HEADING 4, 4, HEADING 4 UNNUMBERED, 4\" \\* MERGEFORMAT ");
                                            // builder.InsertTableOfContents(@"TOC \\o \'1-3\' \\H \\Z \\U 'LIST OF FIGURES,1, LIST OF TABLES,1, LIST OF APPENDICES,1, HEADING 1,1, HEADING 1 UNNUMBERED,1,HEADING 1 UNNUMBERED, HEADING 2,2, HEADING 2 UNNUMBERED,2, HEADING 3,3, HEADING 3 UNNUMBERED,3, HEADING 4,4, HEADING 4 UNNUMBERED,4'");
                                        }
                                        if (!CheckLOF && !CheckLOT && (!TableFlag || (TableFlag && LOTStylename == null)) && (FigureFlag == false || (FigureFlag && LOFStylename == null)))
                                        {
                                            if (doc.Sections[0].PageSetup.Orientation == Orientation.Landscape)
                                            {
                                                builder.CurrentSection.PageSetup.Orientation = Orientation.Portrait;
                                                builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                builder.CurrentSection.PageSetup.Orientation = Orientation.Landscape;
                                            }
                                            else
                                                builder.InsertBreak(BreakType.SectionBreakNewPage);
                                            builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                            if (paraStyle != null)
                                                builder.CurrentParagraph.ParagraphFormat.Style = paraStyle;
                                            builder.CurrentParagraph.Remove();
                                        }
                                        FixToc = true;
                                    }
                                }
                                if (chLst[k].Check_Name == "\"List of Tables\" Heading Style" && chLst[k].Check_Type == 1 && CheckLOT == false && TableFlag == true)
                                {
                                    if (LOTStylename != null)
                                    {
                                        if (TblCaptionFieldseq.Count > 12)
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                        builder.ParagraphFormat.Style = LOTStylename;
                                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                                        builder.Writeln("LIST OF TABLES");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        builder.InsertTableOfContents("TOC \\h \\z \\c \"Table\"");
                                        if (!CheckLOF && (!FigureFlag || (FigureFlag && LOFStylename == null)))
                                        {
                                            if (doc.Sections[0].PageSetup.Orientation == Orientation.Landscape)
                                            {
                                                builder.CurrentSection.PageSetup.Orientation = Orientation.Portrait;
                                                builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                builder.CurrentSection.PageSetup.Orientation = Orientation.Landscape;
                                            }
                                            else
                                                builder.InsertBreak(BreakType.SectionBreakNewPage);
                                            builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                            if (paraStyle != null)
                                                builder.CurrentParagraph.ParagraphFormat.Style = paraStyle;
                                            builder.CurrentParagraph.Remove();
                                        }
                                        FixLot = true;
                                    }

                                }
                                if (chLst[k].Check_Name == "\"List of Figures\" Heading Style" && chLst[k].Check_Type == 1 && !CheckLOF && FigureFlag)
                                {
                                    bool isLotExist = false;
                                    Node TOCEndNode = null;
                                    if (CheckLOT == true)
                                    {
                                        List<Node> FieldNodes = doc.GetChildNodes(NodeType.Any, true).Where(x => (x.NodeType == NodeType.FieldStart || x.NodeType == NodeType.FieldEnd)).ToList();
                                        foreach (Node start in FieldNodes)
                                        {
                                            if (!isLotExist && start.NodeType == NodeType.FieldStart && ((FieldStart)start).FieldType == FieldType.FieldTOC)
                                            {
                                                if (start.ParentNode.Range.Text.Trim().ToUpper().Contains("\"TABLE\""))
                                                    isLotExist = true;
                                            }
                                            if (isLotExist && start.NodeType == NodeType.FieldEnd && ((FieldEnd)start).FieldType == FieldType.FieldTOC)
                                            {
                                                TOCEndNode = start;
                                                break;
                                            }
                                        }
                                    }
                                    if (LOFStylename != null)
                                    {
                                        if (FgrCaptionFieldseq.Count > 12)
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                        builder.ParagraphFormat.Style = LOFStylename;
                                        if (CheckLOT == true)
                                        {
                                            builder.MoveTo(TOCEndNode.ParentNode);
                                        }
                                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                                        builder.Writeln("LIST OF FIGURES");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        builder.InsertTableOfContents("TOC \\h \\z \\c \"Figure\"");
                                        if (doc.Sections[0].PageSetup.Orientation == Orientation.Landscape)
                                        {
                                            builder.CurrentSection.PageSetup.Orientation = Orientation.Portrait;
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                            builder.CurrentSection.PageSetup.Orientation = Orientation.Landscape;
                                        }
                                        else
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        if (paraStyle != null)
                                            builder.CurrentParagraph.ParagraphFormat.Style = paraStyle;
                                        builder.CurrentParagraph.Remove();
                                        FixLof = true;
                                    }
                                }
                            }
                        }
                    }
                    else if (Tocfamily == true && CheckLOT == false && CheckLOF == false && FigureFlag == true && TableFlag == true)
                    {
                        //Below code for adding LOT and LOF
                        bool isTocExisted = false;
                        Node TOCBeginNode = null;
                        Node TOCEndNode = null;
                        List<Node> FieldNodes = doc.GetChildNodes(NodeType.Any, true).Where(x => (x.NodeType == NodeType.FieldStart || x.NodeType == NodeType.FieldEnd || x.NodeType == NodeType.FieldSeparator)).ToList();
                        foreach (Node start in FieldNodes)
                        {
                            if (!isTocExisted && start.NodeType == NodeType.FieldStart && ((FieldStart)start).FieldType == FieldType.FieldTOC)
                            {
                                isTocExisted = true;
                                TOCBeginNode = start;
                            }
                            if (isTocExisted && start.NodeType == NodeType.FieldEnd && ((FieldEnd)start).FieldType == FieldType.FieldTOC)
                            {
                                TOCEndNode = start;
                                break;
                            }
                            if (start.NodeType == NodeType.FieldSeparator && ((FieldSeparator)start).FieldType == FieldType.FieldTOC)
                            {
                                isTocExisted = true;
                                TOCBeginNode = start;
                            }
                        }
                        if (chLst.Count > 0)
                        {
                            DocumentBuilder builder = new DocumentBuilder(doc);
                            for (int k = 0; k < chLst.Count; k++)
                            {
                                chLst[k].Parent_Checklist_ID = rObj.CheckList_ID;
                                chLst[k].JID = rObj.JID;
                                chLst[k].Job_ID = rObj.Job_ID;
                                chLst[k].Folder_Name = rObj.Folder_Name;
                                chLst[k].File_Name = rObj.File_Name;
                                chLst[k].Created_ID = rObj.Created_ID;

                                if (chLst[k].Check_Name == "\"List of Tables\" Heading Style" && chLst[k].Check_Type == 1)
                                {
                                    if (LOTStylename != null)
                                    {
                                        if (TOCEndNode.ParentNode.Range.Text.Trim() != "")
                                        {
                                            Paragraph par = new Paragraph(doc);
                                            if (TOCEndNode.NextSibling != null)
                                            {
                                                Run run = (Run)TOCEndNode.NextSibling;
                                                Paragraph pr1 = (Paragraph)run.ParentParagraph;
                                                pr1.ParentSection.Body.InsertAfter(par, pr1);
                                                builder.MoveTo(par);
                                            }
                                            else
                                                builder.MoveTo(TOCEndNode.ParentNode);
                                        }
                                        else
                                            builder.MoveTo(TOCEndNode.ParentNode);
                                        if (TblCaptionFieldseq.Count > 12)
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                        builder.ParagraphFormat.Style = LOTStylename;
                                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                                        builder.Writeln("LIST OF TABLES");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        builder.InsertTableOfContents("TOC \\h \\z \\c \"Table\"");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        if (paraStyle != null)
                                            builder.CurrentParagraph.ParagraphFormat.Style = paraStyle;
                                        FixLot = true;
                                    }
                                }
                                if (chLst[k].Check_Name == "\"List of Figures\" Heading Style" && chLst[k].Check_Type == 1)
                                {
                                    if (LOFStylename != null)
                                    {
                                        if (FgrCaptionFieldseq.Count > 12)
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                        builder.ParagraphFormat.Style = LOFStylename;
                                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                                        builder.Writeln("LIST OF FIGURES");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        builder.InsertTableOfContents("TOC \\h \\z \\c \"Figure\"");
                                        if (TOCEndNode.ParentNode.NextSibling != null && !TOCEndNode.ParentNode.NextSibling.Range.Text.Contains(ControlChar.PageBreak))
                                        {
                                            if (doc.Sections[0].PageSetup.Orientation == Orientation.Landscape)
                                            {
                                                builder.CurrentSection.PageSetup.Orientation = Orientation.Portrait;
                                                builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                builder.CurrentSection.PageSetup.Orientation = Orientation.Landscape;
                                            }
                                            else
                                                builder.InsertBreak(BreakType.SectionBreakNewPage);
                                            builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                            if (paraStyle != null)
                                                builder.CurrentParagraph.ParagraphFormat.Style = paraStyle;
                                        }
                                        FixLof = true;
                                    }
                                }
                            }
                        }
                    }
                    else if (Tocfamily == true && CheckLOF == false && FigureFlag == true)
                    {
                        //Below code for adding LOF
                        bool isTocExisted = false;
                        Node TOCBeginNode = null;
                        Node TOCEndNode = null;
                        List<Node> FieldNodes = doc.GetChildNodes(NodeType.Any, true).Where(x => (x.NodeType == NodeType.FieldStart || x.NodeType == NodeType.FieldEnd)).ToList();
                        foreach (Node start in FieldNodes)
                        {
                            if (!isTocExisted && start.NodeType == NodeType.FieldStart && ((FieldStart)start).FieldType == FieldType.FieldTOC)
                            {
                                isTocExisted = true;
                                TOCBeginNode = start;
                            }
                            if (isTocExisted && start.NodeType == NodeType.FieldEnd && ((FieldEnd)start).FieldType == FieldType.FieldTOC)
                            {
                                TOCEndNode = start;
                            }
                        }
                        if (chLst.Count > 0)
                        {
                            for (int k = 0; k < chLst.Count; k++)
                            {
                                chLst[k].Parent_Checklist_ID = rObj.CheckList_ID;
                                chLst[k].JID = rObj.JID;
                                chLst[k].Job_ID = rObj.Job_ID;
                                chLst[k].Folder_Name = rObj.Folder_Name;
                                chLst[k].File_Name = rObj.File_Name;
                                chLst[k].Created_ID = rObj.Created_ID;

                                if (chLst[k].Check_Name == "\"List of Figures\" Heading Style" && chLst[k].Check_Type == 1)
                                {
                                    if (LOFStylename != null)
                                    {
                                        DocumentBuilder builder = new DocumentBuilder(doc);
                                        if (TOCEndNode.ParentNode.Range.Text.Trim() != "")
                                        {


                                            Paragraph par = new Paragraph(doc);
                                            if (TOCEndNode.NextSibling != null)
                                            {
                                                Run run = (Run)TOCEndNode.NextSibling;
                                                Paragraph pr1 = (Paragraph)run.ParentParagraph;
                                                pr1.ParentSection.Body.InsertAfter(par, pr1);
                                                builder.MoveTo(par);
                                            }
                                            else
                                                builder.MoveTo(TOCEndNode.ParentNode);
                                        }
                                        else
                                            builder.MoveTo(TOCEndNode.ParentNode);
                                        if (FgrCaptionFieldseq.Count > 12)
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                        builder.ParagraphFormat.Style = LOFStylename;
                                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                                        builder.Writeln("LIST OF FIGURES");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        builder.InsertTableOfContents("TOC \\h \\z \\c \"Figure\"");

                                        if (TOCEndNode.ParentNode.NextSibling != null && !TOCEndNode.ParentNode.NextSibling.Range.Text.Contains(ControlChar.PageBreak))
                                        {
                                            if (doc.Sections[0].PageSetup.Orientation == Orientation.Landscape)
                                            {
                                                builder.CurrentSection.PageSetup.Orientation = Orientation.Portrait;
                                                builder.InsertBreak(BreakType.SectionBreakNewPage);
                                                builder.CurrentSection.PageSetup.Orientation = Orientation.Landscape;
                                            }
                                            else
                                                builder.InsertBreak(BreakType.SectionBreakNewPage);
                                            builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                            if (paraStyle != null)
                                                builder.CurrentParagraph.ParagraphFormat.Style = paraStyle;
                                        }
                                        FixLof = true;
                                    }
                                }
                            }
                        }
                    }
                    else if (Tocfamily == true && CheckLOT == false && TableFlag == true)
                    {
                        //Below Code for adding LOT
                        bool isTocExisted = false;
                        Node TOCBeginNode = null;
                        Node TOCEndNode = null;
                        List<Node> FieldNodes = doc.GetChildNodes(NodeType.Any, true).Where(x => (x.NodeType == NodeType.FieldStart || x.NodeType == NodeType.FieldEnd)).ToList();
                        foreach (Node start in FieldNodes)
                        {
                            if (!isTocExisted && start.NodeType == NodeType.FieldStart && ((FieldStart)start).FieldType == FieldType.FieldTOC)
                            {
                                isTocExisted = true;
                                TOCBeginNode = start;
                            }
                            if (isTocExisted && start.NodeType == NodeType.FieldEnd && ((FieldEnd)start).FieldType == FieldType.FieldTOC)
                            {
                                TOCEndNode = start;
                                break;
                            }
                        }
                        if (chLst.Count > 0)
                        {
                            for (int k = 0; k < chLst.Count; k++)
                            {
                                chLst[k].Parent_Checklist_ID = rObj.CheckList_ID;
                                chLst[k].JID = rObj.JID;
                                chLst[k].Job_ID = rObj.Job_ID;
                                chLst[k].Folder_Name = rObj.Folder_Name;
                                chLst[k].File_Name = rObj.File_Name;
                                chLst[k].Created_ID = rObj.Created_ID;

                                if (chLst[k].Check_Name == "\"List of Tables\" Heading Style" && chLst[k].Check_Type == 1)
                                {
                                    if (LOTStylename != null)
                                    {
                                        DocumentBuilder builder = new DocumentBuilder(doc);
                                        if (TOCEndNode.ParentNode.Range.Text.Trim() != "")
                                        {
                                            Paragraph par = new Paragraph(doc);
                                            if (TOCEndNode.NextSibling != null)
                                            {
                                                Run run = (Run)TOCEndNode.NextSibling;
                                                Paragraph pr1 = (Paragraph)run.ParentParagraph;
                                                pr1.ParentSection.Body.InsertAfter(par, pr1);
                                                builder.MoveTo(par);
                                            }
                                            else
                                                builder.MoveTo(TOCEndNode.ParentNode);
                                            //if (TOCEndNode.ParentNode.PreviousSibling!=null && TOCEndNode.ParentNode.PreviousSibling.NodeType==NodeType.Paragraph)
                                            //{
                                            //    Paragraph par = new Paragraph(doc);
                                            //    Run run = (Run)TOCEndNode.NextSibling;
                                            //    Paragraph pr1 = (Paragraph)TOCEndNode.ParentNode;
                                            //     pr1.ParentSection.Body.InsertBefore(par, pr1);
                                            //     builder.MoveTo(par);
                                            // //   Field fields = null;
                                            // //foreach(Field fld in TOCEndNode.ParentNode.PreviousSibling.Range.Fields)
                                            // //   {
                                            // //       fields = fld;
                                            // //       break;
                                            // //   }
                                            // //   pr1.ParentNode.InsertBefore(par, pr1);
                                            // //   int indx = doc.FirstSection.ChildNodes.IndexOf(TOCEndNode.ParentNode);                                                
                                            // //   builder.MoveToField(fields, false);
                                            //    //builder1.InsertBreak(BreakType.PageBreak);
                                            //}                                            
                                            //else
                                            //    builder.MoveTo(TOCEndNode.ParentNode);
                                        }
                                        else
                                            builder.MoveTo(TOCEndNode.ParentNode);
                                        if (TblCaptionFieldseq.Count > 12)
                                            builder.InsertBreak(BreakType.SectionBreakNewPage);
                                        builder.ParagraphFormat.Style = LOTStylename;
                                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                                        builder.Writeln("LIST OF TABLES");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        builder.InsertTableOfContents("TOC \\h \\z \\c \"Table\"");
                                        builder.CurrentParagraph.ParagraphFormat.ClearFormatting();
                                        if (paraStyle != null)
                                            builder.CurrentParagraph.ParagraphFormat.Style = paraStyle;
                                        FixLot = true;
                                    }
                                }
                            }
                        }
                    }
                    if (FixToc == true && FixLot == true && FixLof == true)
                    {
                        //rObj.QC_Result = "Fixed";
                        rObj.Is_Fixed = 1;
                        rObj.Comments = "TOC,LOT and LOF are Created by RegAi.";
                    }
                    else if (FixToc == true && FixLot == true && FixLof == false)
                    {
                        //rObj.QC_Result = "Fixed";
                        rObj.Is_Fixed = 1;
                        rObj.Comments = "TOC and LOT are Created by RegAi.";
                    }
                    else if (FixToc == true && FixLot == false && FixLof == true)
                    {
                        //rObj.QC_Result = "Fixed";
                        rObj.Is_Fixed = 1;
                        rObj.Comments = "TOC and LOF are Created by RegAi.";
                    }
                    else if (FixToc == false && FixLot == true && FixLof == true)
                    {
                        //rObj.QC_Result = "Fixed";
                        rObj.Is_Fixed = 1;
                        rObj.Comments = "LOT and LOF are Created by RegAi.";
                    }
                    else if (FixToc == true && FixLot == false && FixLof == false)
                    {
                        //rObj.QC_Result = "Fixed";
                        rObj.Is_Fixed = 1;
                        rObj.Comments = "TOC Created by RegAi.";
                    }
                    else if (FixToc == false && FixLot == false && FixLof == true)
                    {
                        //rObj.QC_Result = "Fixed";
                        rObj.Is_Fixed = 1;
                        rObj.Comments = "LOF Created by RegAi.";
                    }
                    else if (FixToc == false && FixLot == true && FixLof == false)
                    {
                        //rObj.QC_Result = "Fixed";
                        rObj.Is_Fixed = 1;
                        rObj.Comments = "LOT Created by RegAi.";
                    }
                    if (CheckStyles != null && CheckStyles != "")
                    {
                        CheckStyles = CheckStyles.Substring(0, CheckStyles.Length - 1);
                        rObj.Comments = rObj.Comments + "," + CheckStyles + " styles not exist in the document.";
                        rObj.Comments = rObj.Comments.Replace("Given styles applied for existing toc,", "");
                    }
                    if (PredictFlag)
                    {
                        //rObj.QC_Result = "Fixed";
                        rObj.Is_Fixed = 1;
                        if (!rObj.Comments.Contains("Given styles applied for existing toc") || (FinalComment != null && FinalComment != ""))
                            rObj.Comments = FinalComment + "These are fixed," + rObj.Comments;
                        rObj.Comments = rObj.Comments.Replace("Given styles applied for existing toc,", "");
                    }
                    if (rObj.Is_Fixed != 1 && (CheckFix || rObj.Comments.Trim() == "TOC and LOT are present" || rObj.Comments == "TOC and LOF are present" || rObj.Comments == "TOC present" || rObj.Comments == "This Check is passed"))
                    {
                        rObj.QC_Result = "Passed";
                    }
                }
                doc.UpdateFields();
                doc.Save(rObj.DestFilePath);
                rObj.CHECK_END_TIME = DateTime.Now;
            }
            catch (Exception ex)
            {
                ErrorLogger.Error("JOB_ID:" + rObj.Job_ID + ", CHECK NAME: " + rObj.Check_Name + "\n" + ex);
                rObj.Job_Status = "Error";
                rObj.QC_Result = "Error";
                rObj.Comments = "Technical error: " + ex.Message;
            }
        }

can you help for above issue

@k.sukumar We are working on your query and will reply soon.

@k.sukumar,
To get the desired result you can remove unwanted TOC and unwanted paragraphs from your output document after producing it. Please check the following code example:

public static void RemoveTableOfContents(Document doc, int index)
{
    // Store the FieldStart nodes of TOC fields in the document for quick access.
    ArrayList fieldStarts = new ArrayList();
    // This is a list to store the nodes found inside the specified TOC. They will be removed
    // At the end of this method.
    ArrayList nodeList = new ArrayList();

    foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true))
    {
        if (start.FieldType == FieldType.FieldTOC)
        {
            // Add all FieldStarts which are of type FieldTOC.
            fieldStarts.Add(start);
        }
    }

    // Ensure the TOC specified by the passed index exists.
    if (index > fieldStarts.Count - 1)
        throw new ArgumentOutOfRangeException("TOC index is out of range");

    bool isRemoving = true;
    // Get the FieldStart of the specified TOC.
    Node currentNode = (Node)fieldStarts[index];

    while (isRemoving)
    {
        // It is safer to store these nodes and delete them all at once later.
        nodeList.Add(currentNode);
        currentNode = currentNode.NextPreOrder(doc);

        // Once we encounter a FieldEnd node of type FieldTOC then we know we are at the end
        // Of the current TOC and we can stop here.
        if (currentNode.NodeType == NodeType.FieldEnd)
        {
            FieldEnd fieldEnd = (FieldEnd)currentNode;
            if (fieldEnd.FieldType == FieldType.FieldTOC)
                isRemoving = false;
        }
    }

    // Remove all nodes found in the specified TOC.
    foreach (Node node in nodeList)
    {
        node.Remove();
    }
}
Document doc = new Document(@"C:\Temp\32p531-val-of-analytical-proc-benzyl alcohol (1).doc");
DocumentBuilder builder = new DocumentBuilder(doc);

// removing unwanted TOC (list of tables) from document
RemoveTableOfContents(doc, 1);

//removing unwanted paragraps from first TOC and from document
int num = 1;
foreach (Node p in doc.GetChildNodes(NodeType.Paragraph, true))
{
    if (p.GetText().Contains("LIST OF TABLES"))
    {
        if (num == 1)
            p.Remove();

        if (num == 3)
        {
            builder.MoveTo(p.NextSibling);
            p.Remove();
            break;
        }

        num += 1;
    }
}

builder.InsertBreak(BreakType.PageBreak);


doc.Save(@"C:\Temp\32p531-val-of-analytical-proc-benzyl alcohol (1)-updated.doc");

Please also check the attached document, produced by the code above.
32p531-val-of-analytical-proc-benzyl alcohol (1)-updated.zip (59.0 KB)

Thanks for the help @sergey.lobanov but how can put this code in visual studio should i put this code after static void main or else should i put this code above static void main . you have send two codes iam not getting exact idea which code i need to take first…please help me

@k.sukumar,
First block of code is function, that removes an unwanted TOC of specified index from the document. Please put this function into the namespace of your project.

Second block of code is code, that uses the function above to remove unwanted TOC (in your case, the TOC with index 1), and then removes unwanted paragraphs (the paraghraps with “LIST OF TABLES” in their text, one from first TOC and one from document body) from your document.
Please put this code after producing your document (32p531-val-of-analytical-proc-benzyl alcohol (1).docx).

thank you so much @sergey.lobanov

Hi @alexey.noskov ,

I’m facing an issue when removing section break, I have attached the document in that when I removed the section break on the first page the header was also removed. i have used this code to remove section section break.

private static void RemoveSectionBreaks(Document doc)
{
    // Loop through all sections starting from the section that precedes the last one 
    // And moving to the first section.
    for (int i = doc.Sections.Count - 2; i >= 0; i--)
    {
        // Copy the content of the current section to the beginning of the last section.
        doc.LastSection.PrependContent(doc.Sections[i]);
        // Remove the copied section.
        doc.Sections[i].Remove();
    }
}

can you help me to remove only section break not the header in the first page docQC28738_Output_O-3.2.A.1 Facilities and Equipment-Pfizer Grange Castle.zip (43.3 KB)

Hi Hafeez,
I’m facing an issue when removing section break, I have attached the document in that when I removed the section break on the first page the header was also removed. i have used this code to remove section break.
QC28738_Output_O-3.2.A.1 Facilities and Equipment-Pfizer Grange Castle.zip (43.3 KB)

private static void RemoveSectionBreaks(Document doc)
{
    // Loop through all sections starting from the section that precedes the last one 
    // And moving to the first section.
    for (int i = doc.Sections.Count - 2; i >= 0; i--)
    {
        // Copy the content of the current section to the beginning of the last section.
        doc.LastSection.PrependContent(doc.Sections[i]);
        // Remove the copied section.
        doc.Sections[i].Remove();
    }
}

can you help me to remove only the section break not the header in the first-page doc

@k.sukumar The problem occurs because headers and footers are defined in the first section of your document, but in your code you copy all content into the last section and remove the first section. You can modify your code like the following to get the desired result:

private static void RemoveSectionBreaks(Document doc)
{
    // Append all content to the first section of the document.
    while (doc.Sections.Count > 1)
    {
        doc.FirstSection.AppendContent(doc.Sections[1]);
        doc.Sections[1].Remove();
    }
}

However, you should note that different sections might have different headers/footers and if you remove all section breaks you will have headers/footers only from one section.

1 Like

thank you very much @alexey.noskov.

Hi @alexey.noskov,

i have attached the document in that document I am trying to remove the page break in the first page but it is not removed QC28881_Output_3.2.S.4.3.2 Validation of Analyt. Procedure( BET) - Cambrex.zip (20.6 KB)
can you help me to remove that page break in the first page .

I have tried this code but have not removed it.

Document doc = new Document(MyDir + "Remove page breaks.docx");
// Retrieve all paragraphs in the document.
NodeCollection paragraphs = doc.GetChildNodes(NodeType.Paragraph, true);
foreach (Paragraph para in paragraphs)
{
	// If the paragraph has a page break set before, then clear it.
	if (para.ParagraphFormat.PageBreakBefore)
		para.ParagraphFormat.PageBreakBefore = false;
	// Check all runs in the paragraph for page breaks and remove them.
	foreach (Run run in para.Runs)
		if (run.Text.Contains(ControlChar.PageBreak))
			run.Text = run.Text.Replace(ControlChar.PageBreak, string.Empty);
}