NumberingInstance

We found 10 examples in language CSharp for this search. You will see 44 fragments of code.

    public override OpenXmlElement CloneNode(bool deep)
    {
      return (OpenXmlElement) this.CloneImp<NumberingInstance>(deep);
    }

        static void Main(string[] args)
        {
            WordDocument doc = new WordDocument();

            NumberingLevel level0 = new NumberingLevel();
            level0.Level = 0;
            level0.Start = 1;
            level0.Justification = HorizontalAlignmentType.Left;
            level0.Format = NumberingFormat.Bullet;
            level0.RunProperties.Fonts.AsciiFont = "Wingdings";
            level0.RunProperties.Fonts.HighAnsiFont = "Wingdings";

            byte[] bulletBuffer = new byte[3];
            bulletBuffer[0] = (byte)239;
            bulletBuffer[1] = (byte)130;
            bulletBuffer[2] = (byte)167;

            level0.Text = new NumberingLevelText(System.Text.Encoding.UTF8.GetString(bulletBuffer));

            AbstractNumbering abstractNumbering = new AbstractNumbering();
            abstractNumbering.ID = 1;
            abstractNumbering.Levels.Add(level0);

            NumberingReference numbering1 = new NumberingReference(2);
            numbering1.NumberingLevelID = 0;
            numbering1.NumberingID = 1;

            NumberingDefinitionInstance numberingInstance = new NumberingDefinitionInstance();
            numberingInstance.ID = 1;
            numberingInstance.AbstractNumberingID = 1;

            NumberingDefinitions numberingDefinitions = new NumberingDefinitions();
            numberingDefinitions.Numberings.Add(numberingInstance);
            numberingDefinitions.AbstractNumberings.Add(abstractNumbering);

            doc.NumberingDefinitions = numberingDefinitions;

            Run run1 = new Run();
            run1.AddText("First");

            Run run2 = new Run();
            run2.AddText("Second");

            Run run3 = new Run();
            run3.AddText("Third");

            Paragraph paragraph1 = new Paragraph();
            paragraph1.Add(run1);
            paragraph1.NumberingReference = numbering1;

            Paragraph paragraph2 = new Paragraph();
            paragraph2.Add(run2);
            paragraph2.NumberingReference = numbering1;

            Paragraph paragraph3 = new Paragraph();
            paragraph3.Add(run3);
            paragraph3.NumberingReference = numbering1;

            doc.Body.Add(paragraph1);
            doc.Body.Add(paragraph2);
            doc.Body.Add(paragraph3);

            doc.Save("c:\\test\\output.docx", true);
        }


        public void ApplyStyle(Paragraph paragraph, FontStyles style, int level)
        {
            paragraph.ApplyStyleId("ListParagraph");
            var listId = GetListStyleId(style);
            paragraph.AppendChild(new NumberingProperties()
            {
                NumberingLevelReference = new NumberingLevelReference() { Val = level },
                NumberingId = new NumberingId() { Val = listId }
            });
        }

        private int CreateAbstractNum(FontStyles style)
        {
            var abstractNumberId = _numberingPart.Numbering.Elements<AbstractNum>().Count() + 1;
            AbstractNum abstractNum = new()
            {
                AbstractNumberId = abstractNumberId,
                MultiLevelType = new MultiLevelType() {Val = MultiLevelValues.Multilevel}
            };
            switch (style)
            {
                case FontStyles.NumberList:
                    AddNumberListLevels(abstractNum);
                    break;
                case FontStyles.BulletList:
                    AddBulletListLevels(abstractNum);
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(style), style, null);
            }

            if (abstractNumberId == 1)
            {
                _numberingPart.Numbering.AppendChild(abstractNum);
            }
            else
            {
                AbstractNum lastAbstractNum = _numberingPart.Numbering.Elements<AbstractNum>().Last();
                _numberingPart.Numbering.InsertAfter(abstractNum, lastAbstractNum);
            }

            return abstractNumberId;
        }

        private static string GetNumberingTextTemplate(int level)
        {
            var sb = new StringBuilder();
            for (int i = 0; i < level; i++)
            {
                sb.Append($"%{i + 1}.");
            }

            return sb.ToString();
        }

        private static void AddNumberListLevels(AbstractNum abstractNum)
        {
            var maxLevel = Math.Min(10, FontStyles.NumberList.GetMaxLevel());
            for (int i = 0, indStart = IndStart; i < maxLevel; i++, indStart += IndStep)
            {
                var level = new Level()
                {
                    LevelIndex = i,
                    NumberingFormat = new NumberingFormat { Val = NumberFormatValues.Decimal },
                    StartNumberingValue = new StartNumberingValue {Val = 1},
                    LevelText = new LevelText { Val = GetNumberingTextTemplate(i + 1) },
                    LevelJustification = new LevelJustification() {Val = LevelJustificationValues.Left},
                    PreviousParagraphProperties = new PreviousParagraphProperties() {Indentation = new Indentation() {Left = indStart.ToString(), Hanging = IndStart.ToString()}}
                };
                abstractNum.AppendChild(level);        
            }
        }

        private static void AddBulletListLevels(AbstractNum abstractNum)
        {
            var maxLevel = Math.Min(10, FontStyles.BulletList.GetMaxLevel());
            for (int i = 0, indStart = IndStart; i < maxLevel; i++, indStart += IndStep)
            {
                var level = new Level()
                {
                    LevelIndex = i,
                    NumberingFormat = new NumberingFormat { Val = NumberFormatValues.Bullet },
                    LevelText = new LevelText { Val = "" },
                    LevelJustification = new LevelJustification() {Val = LevelJustificationValues.Left},
                    PreviousParagraphProperties = new PreviousParagraphProperties()
                    {
                        Indentation = new Indentation() {Left = indStart.ToString(), Hanging = IndStart.ToString()}
                    },
                    NumberingSymbolRunProperties = new NumberingSymbolRunProperties()
                    {
                        RunFonts = new RunFonts() {Ascii = "Symbol", HighAnsi = "Symbol", Hint = FontTypeHintValues.Default}
                    }
                };
                abstractNum.AppendChild(level);        
            }
        }
        private int CreateNumberingInstance(int abstractNumberId)
        {
            var numberId = _numberingPart.Numbering.Elements<NumberingInstance>().Count() + 1;
            NumberingInstance numberingInstance1 = new() { NumberID = numberId };
            AbstractNumId abstractNumId1 = new() { Val = abstractNumberId };
            numberingInstance1.AppendChild(abstractNumId1);

            if (numberId == 1)
            {
                _numberingPart.Numbering.AppendChild(numberingInstance1);
            }
            else
            {
                var lastNumberingInstance = _numberingPart.Numbering.Elements<NumberingInstance>().Last();
                _numberingPart.Numbering.InsertAfter(numberingInstance1, lastNumberingInstance);
            }

            return numberId;
        }


        private void PrepareWordElements()
        {
            elements = new List<DocxElement>() {
                new DocxDiv(this),
                new DocxUL(this),
                new DocxOL(this),
                new DocxImage(this),
                new DocxSpan(this),
                new DocxA(this),
                new DocxBr(this),
                new DocxUnderline(this),
                new DocxCenter(this),
                new DocxItalic(this),
                new DocxBold(this),
                new DocxHeading(this),
                new DocxHeader(this),
                new DocxFooter(this),
                new DocxAddress(this),
                new DocxSection(this),
                new DocxFont(this),
                new DocxDL(this),
                new DocxHr(this),
                new DocxQ(this),
                new DocxSup(this),
                new DocxSub(this),
                new DocxStrike(this),
                new DocxObject(this),
                new DocxTable(this),
                new DocxInline(this)
            };

            textElements = new List<ITextElement>() {
                new DocxBold(this),
                new DocxSpan(this),
                new DocxBr(this),
                new DocxCenter(this),
                new DocxItalic(this),
                new DocxUnderline(this),
                new DocxImage(this),
                new DocxDiv(this),
                new DocxHeader(this),
                new DocxFooter(this),
                new DocxFont(this),
                new DocxQ(this),
                new DocxSup(this),
                new DocxSub(this),
                new DocxStrike(this),
                new DocxObject(this),
                new DocxInline(this)
            };
        }

        private void SaveNumberDefinitions()
        {
            if (abstractNumList != null && numberingInstanceList != null)
            {
                if (mainPart.NumberingDefinitionsPart == null)
                {
                    _ = mainPart.AddNewPart<NumberingDefinitionsPart>("numberingDefinitionsPart");
                }

                Numbering numbering = new Numbering();

                foreach (var abstractNum in abstractNumList)
                {
                    numbering.Append(abstractNum.Value);
                }

                foreach (var numberingInstance in numberingInstanceList)
                {
                    numbering.Append(numberingInstance.Value);
                }

                mainPart.NumberingDefinitionsPart.Numbering = numbering;
            }
        }

        public void Save()
        {
            SaveNumberDefinitions();

            Document.Save();

            document.Close();
            document.Dispose();

            document = null;
            mainPart = null;
        }

        public DocxElement Convert(DocxNode node)
        {
            foreach (DocxElement element in elements)
            {
                if (element.CanConvert(node))
                {
                    return element;
                }
            }

            return null;
        }

        public ITextElement ConvertTextElement(DocxNode node)
        {
            foreach (ITextElement element in textElements)
            {
                if (element.CanConvert(node))
                {
                    return element;
                }
            }

            return null;
        }

        public DocxElement GetBodyElement()
        {
            return new DocxBody(this);
        }




        [HttpPost]
        public async Task<IActionResult> Index(string urlName)
        {
            if (string.IsNullOrWhiteSpace(urlName))
            {
                ModelState.AddModelError("urlName", "Recording URL is required.");
                return View();
            }
            string title = "Transcom";
            try
            {              
                List<string> sentences = new List<string>();
                string[] s = urlName.Split('/');
                string videoId = s.Last();
                string token = "";
                string textTrackUrl = "https://euno-1.api.microsoftstream.com/api/videos/" + videoId + "/texttracks?api-version=1.4-private";
                string titleUrl = "https://euno-1.api.microsoftstream.com/api/videos/" + videoId + "?$expand=creator,tokens,status,liveEvent,extensions&api-version=1.4-private";

                string vttUrl = "";

                HttpResponseMessage urlResponse = await GetHttpResponse(textTrackUrl, token);
                if (urlResponse.IsSuccessStatusCode)
                {
                    var textTracksResponseString = await urlResponse.Content.ReadAsStringAsync();
                    TextTracksResponse textTracksResponse = JsonConvert.DeserializeObject<TextTracksResponse>(textTracksResponseString);
                    vttUrl = textTracksResponse?.value?[0].url;
                }
                else
                {
                    ModelState.AddModelError("urlName", " Video not found in URL.");
                    return View();
                }


                HttpResponseMessage titleResponse = await GetHttpResponse(titleUrl, token);
                if (titleResponse.IsSuccessStatusCode)
                {
                    var textTracksResponseString = await titleResponse.Content.ReadAsStringAsync();
                    var responseJObject = JObject.Parse(textTracksResponseString);
                    title = (string)responseJObject["name"];
                }


                sentences = ExtractVttContent(token, vttUrl);

                //Create Word file
                string fileName = title + ".docx";
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
                CreateWordprocessingDocument(path, title, sentences);
                TempData["Path"] = "";
                TempData["Path"] = path;
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("file", string.Format("Can you please close {0} file.", title));
                return View();
            }

            return View();
        }

        private async Task<HttpResponseMessage> GetHttpResponse(string url, string token)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("authorization", token);
                HttpResponseMessage response = await client.GetAsync(url);

                return response;
            }
        }

        private static List<string> ExtractVttContent(string token, string vttUrl)
        {
            List<string> sentences = new List<string>();
            using (var client = new WebClient())
            {

                client.Headers.Clear();

                client.Headers.Add("authorization", token);
                var content = client.DownloadData(vttUrl);
                using (var stream = new MemoryStream(content))
                {
                    string fileName = "file.txt";
                    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
                    FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write);
                    stream.WriteTo(file);
                    file.Close();

                    SubtitlesParser.Classes.Parsers.SubParser parser = new SubtitlesParser.Classes.Parsers.SubParser();

                    using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                    {
                        try
                        {
                            var mostLikelyFormat = parser.GetMostLikelyFormat(fileStream.Name);
                            var items = parser.ParseStream(fileStream, Encoding.UTF8, mostLikelyFormat);

                            string sentence = " ";
                            foreach (var item in items)
                            {
                                foreach (var line in item.Lines)
                                {
                                    foreach (var word in line.ToCharArray())
                                    {
                                        sentence = sentence + word;

                                        if (word.Equals('.') || word.Equals('?'))
                                        {
                                            sentences.Add(sentence);
                                            sentence = string.Empty;
                                        }
                                    }
                                    sentence = sentence + " ";
                                }
                            }
                            //Remove small talks from trans script sentences
                            RemoveSmallTalks(sentences);
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
            }
            return sentences;
        }

        private static void RemoveSmallTalks(List<string> sentences)
        {
            List<string> smallTalks = new List<string>();
            foreach (string sm in SmallTalkDictionary.smallTalks)
            {
                smallTalks.AddRange(sentences.FindAll(s => s.ToLower().Contains(sm.ToLower())));
            }
            sentences?.RemoveAll(st => smallTalks.Contains(st));
        }

        [HttpGet]
        public async Task<IActionResult> Download(string path)
        {
            var memory = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            var ext = Path.GetExtension(path).ToLowerInvariant();
            return File(memory, GetMimeTypes()[ext], Path.GetFileName(path));
        }

        public void CreateWordprocessingDocument(string filepath, string title, List<string> conversation)
        {
            // Create a document by supplying the filepath. 
            using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                // Add a main document part. 
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                AddSettingsToMainDocumentPart(mainPart);

                // Create the document structure and add some text.
                Document doc = new Document();

                HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>("rId7");
                GenerateHeader(headerPart);

                Body body = new Body();
                // 1 paragrafo
                Paragraph para = new Paragraph();

                ParagraphProperties paragraphProperties1 = new ParagraphProperties();
                ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Bold" };
                Justification justification1 = new Justification() { Val = JustificationValues.Center };
                ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();

                paragraphProperties1.Append(paragraphStyleId1);
                //paragraphProperties1.Append(fontSize1);
                paragraphProperties1.Append(justification1);
                paragraphProperties1.Append(paragraphMarkRunProperties1);

                Run run = new Run();
                RunProperties runProperties1 = new RunProperties(new FontSize() { Val = "50" }, new Bold() { Val = OnOffValue.FromBoolean(true) });

                Text text = new Text() { Text = title };

                // siga a ordem 
                run.Append(runProperties1);
                run.Append(text);
                para.Append(paragraphProperties1);
                para.Append(run);
                body.Append(para);
                //Paragraph titlePara = CreateParagraph( title, JustificationValues.Center);
                //body.Append(titlePara);

                // "Here are the discussed points:" Paragraph
                Paragraph pointsHeaderPara = CreateParagraph("Here are the discussed points:", JustificationValues.Left);

                body.Append(pointsHeaderPara);

                foreach (var line in conversation)
                {
                    Paragraph paragraph1 = CreateParagraphForBullets(line, wordDocument);
                    body.Append(paragraph1);
                }

                doc.Append(body);

                wordDocument.MainDocumentPart.Document = doc;

                wordDocument.Close();
            }
        }


        private Paragraph CreatePar(string style)
        {
            Paragraph p1 = new Paragraph();
            p1.PrependChild<ParagraphProperties>(new ParagraphProperties(new ParagraphStyleId() { Val = style }));
            wordprocessingDocument.MainDocumentPart.Document.Body.AppendChild(p1);
            return p1;
        }

        private Paragraph CreatePar(string style, string text)
        {
            var p1 = CreatePar(style);
            p1.AppendChild(new Run(new Text(text)));
            return p1;
        }

        private void CreateRun(Paragraph par, string style, string text, bool addBreak = true)
        {
            Run run = new Run(new Text(text));
            run.PrependChild<RunProperties>(new RunProperties(new RunStyle() { Val = style }));
            par.AppendChild(run);
            if (addBreak)
                par.AppendChild(new Break());
        }

        public void Run(Models.Formular formular, bool showAnswers, System.IO.Stream stream)
        {
            this.wordprocessingDocument = WordprocessingDocument.Open(stream, true);

            wordprocessingDocument.MainDocumentPart.Document.Body.RemoveAllChildren();
            
            // projit sekce
            foreach (Models.Sekce sekce in formular.Sekce)
            {
                CreatePar(StyleName_SegmentTitle, sekce.Base.f18Name);

                // popis sekce
                if (!string.IsNullOrEmpty(sekce.Base.f18Text))
                    CreatePar(StyleName_SegmentText, sekce.Base.f18Text);

                // supporting text
                if (!string.IsNullOrEmpty(sekce.Base.f18SupportingText))
                    CreatePar(StyleName_SegmentSupportingText, sekce.Base.f18SupportingText);

                // najit otazky pro sekci
                foreach (UIFT.Models.IOtazka otazka in formular.Otazky.FindAll(t => t.IdSekce == sekce.Base.pid))
                {
                    // otazky, ktere se netisknou
                    if (otazka.ReplyControl == BO.ReplyKeyEnum.Button)
                        continue;

                    // hlavicka otazky
                    BuildQuestionHeader(otazka);
                    
                    // telo otazky - tj. odpovedi
                    BuildQuestionBody(otazka, showAnswers);

                    // pokud otazka obsahuje moznost komentare
                    if (otazka.Odpovedi != null)
                    {
                        if (otazka.Odpovedi.Exists(t => t.f21IsCommentAllowed))
                        {
                            BO.f32FilledValue fillComm = otazka.VyplneneOdpovedi.FirstOrDefault(t => t.f21ID == otazka.Odpovedi.Find(t2 => t2.f21IsCommentAllowed).pid);
                            if (fillComm != null && showAnswers)
                                BuildComment(fillComm.f32Comment);
                            else
                                BuildComment();
                        }
                    }

                    wordprocessingDocument.MainDocumentPart.Document.Body.AppendChild(new Paragraph());
                }
            }

            wordprocessingDocument.Close();
        }

        /// <summary>
        /// Vytvori telo otazky, tj. jednotlive odpovedi
        /// </summary>
        private void BuildQuestionBody(Models.IOtazka otazka, bool showAnswers)
        {
            switch (otazka.ReplyControl)
            {
                case BO.ReplyKeyEnum.FileUpload:
                    if (otazka.VyplneneOdpovedi.Count > 0 && showAnswers)
                        BuildTextArea(1, otazka.VyplneneOdpovedi[0].Value);
                    else
                        BuildTextArea(1);
                    break;

                case BO.ReplyKeyEnum.RadiobuttonList:
                case BO.ReplyKeyEnum.DropdownList:
                    BuildAnswerHint(_Repository.BL.tra("Zaškrtněte jednu odpověď."));
                    // jednotlive odpovedi
                    BuildListAnswers(otazka.Odpovedi, showAnswers ? otazka.VyplneneOdpovedi : null);
                    break;

                case BO.ReplyKeyEnum.Listbox:
                case BO.ReplyKeyEnum.Checkbox:
                    if (((Models.Otazka)otazka).Base.f19IsMultiselect) // checkboxy
                    {
                        BuildAnswerHint("Můžete zaškrtnout i více odpovědí najednou.");
                    }
                    else // radio boxy
                    {
                        BuildAnswerHint("Zaškrtněte jednu odpověď.");
                    }

                    // jednotlive odpovedi
                    BuildListAnswers(otazka.Odpovedi, showAnswers ? otazka.VyplneneOdpovedi : null);
                    break;

                case BO.ReplyKeyEnum.TextBox:
                    Models.Otazka otazka2 = (Models.Otazka)otazka;

                    // slozit napovedu pro min a max hodnoty
                    #region slozit napovedu pro min a max hodnoty
                    if (!string.IsNullOrEmpty(otazka2.Base.TextBox_MinValue) || !string.IsNullOrEmpty(otazka2.Base.TextBox_MaxValue))
                    {
                        string hint = "", minVal = "", maxVal = "";
                        switch (otazka.ReplyType)
                        {
                            case BO.x24DataTypeEnum.tDecimal:
                            case BO.x24DataTypeEnum.tInteger:
                                if (!string.IsNullOrEmpty(otazka2.Base.TextBox_MinValue))
                                    minVal = otazka2.Base.TextBox_MinValue.ConvertFromBL().ToString(_config.UIFT_DateFormat);
                                if (!string.IsNullOrEmpty(otazka2.Base.TextBox_MaxValue))
                                    maxVal = otazka2.Base.TextBox_MaxValue.ConvertFromBL().ToString(_config.UIFT_DateFormat);
                                break;
                            default:
                                minVal = otazka2.Base.TextBox_MinValue;
                                maxVal = otazka2.Base.TextBox_MaxValue;
                                break;
                        }

                        if (!string.IsNullOrEmpty(minVal))
                            hint = "Min. hodnota: " + minVal;
                        if (!string.IsNullOrEmpty(maxVal))
                        {
                            if (hint != "")
                                hint += ", ";
                            hint = "Max. hodnota: " + maxVal;
                        }
                        BuildAnswerHint(hint);
                    }
                    #endregion

                    if (otazka.VyplneneOdpovedi.Count > 0 && showAnswers)
                    {
                        string txt = otazka.VyplneneOdpovedi[0].Value;
                        switch (otazka.ReplyType)
                        {
                            case BO.x24DataTypeEnum.tDateTime:
                                txt = txt.ConvertFromBL().ToString(_config.UIFT_DateTimeFormat);
                                break;
                            case BO.x24DataTypeEnum.tDate:
                                txt = txt.ConvertFromBL().ToString(_config.UIFT_DateFormat);
                                break;
                        }
                        BuildTextArea(1, txt);
                    }
                    else
                        BuildTextArea(1);
                    break;

                // html
                case BO.ReplyKeyEnum.HtmlEditor:
                    if (otazka.VyplneneOdpovedi.Count > 0 && showAnswers)
                        BuildTextArea(defaultText: otazka.VyplneneOdpovedi[0].Value);
                    else
                        BuildTextArea();
                    break;
            }
        }

        /// <summary>
        /// Vytvori seznam odpovedi v Bullet listu
        /// </summary>
        private void BuildListAnswers(List<BO.f21ReplyUnitJoinedF19> odpovedi, List<BO.f32FilledValue> vyplneneOdpovedi)
        {
            Paragraph par = new Paragraph();
            par.PrependChild<ParagraphProperties>(new ParagraphProperties()
            {
                ContextualSpacing = new ContextualSpacing() { Val = OnOffValue.FromBoolean(true) }
            });

            var runList = new List<Run>();
            foreach (var odpoved in odpovedi)
            {
                var newRun = new Run();
                    
                if (vyplneneOdpovedi != null)
                {
                    BO.f32FilledValue val = vyplneneOdpovedi.FirstOrDefault(t => t.f21ID == odpoved.pid);
                    if (val != null)
                    {
                        if (val.Value == _config.FT_CheckboxAnswerTrueValue)
                            newRun.PrependChild<RunProperties>(new RunProperties() { Bold = new Bold() { Val = new OnOffValue(true) }, Color = new Color() { Val = "green" } });
                    }
                }

                newRun.AppendChild(new Text(odpoved.f21Name));
                runList.Add(newRun);
            }

            AddBulletList(runList);
        }



		#region InitNumberingIds

		private void InitNumberingIds()
		{
			NumberingDefinitionsPart numberingPart = mainPart.NumberingDefinitionsPart;
			int absNumIdRef = 0;

			// Ensure the numbering.xml file exists or any numbering or bullets list will results
			// in simple numbering list (1.   2.   3...)
			if (numberingPart == null)
				numberingPart = numberingPart = mainPart.AddNewPart<NumberingDefinitionsPart>();

			if (mainPart.NumberingDefinitionsPart.Numbering == null)
			{
				new Numbering().Save(numberingPart);
			}
			else
			{
				// The absNumIdRef Id is a required field and should be unique. We will loop through the existing Numbering definition
				// to retrieve the highest Id and reconstruct our own list definition template.
				foreach (var abs in numberingPart.Numbering.Elements<AbstractNum>())
				{
					if (abs.AbstractNumberId.HasValue && abs.AbstractNumberId > absNumIdRef)
						absNumIdRef = abs.AbstractNumberId;
				}
				absNumIdRef++;
			}

			// This minimal numbering definition has been inspired by the documentation OfficeXMLMarkupExplained_en.docx
			// http://www.microsoft.com/downloads/details.aspx?FamilyID=6f264d0b-23e8-43fe-9f82-9ab627e5eaa3&displaylang=en

			DocumentFormat.OpenXml.OpenXmlElement[] absNumChildren = new [] {
				//8 kinds of abstractnum + 1 multi-level.
				new AbstractNum(
					new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
					new Level {
						StartNumberingValue = new StartNumberingValue() { Val = 1 },
						NumberingFormat = new NumberingFormat() { Val = NumberFormatValues.Decimal },
						LevelIndex = 0,
						LevelText = new LevelText() { Val = "%1." },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = "420", Hanging = "360" }
						}
					}
				) { AbstractNumberId = absNumIdRef },
				new AbstractNum(
					new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
					new Level {
						NumberingFormat = new NumberingFormat() { Val = NumberFormatValues.Bullet },
						LevelIndex = 0,
						LevelText = new LevelText() { Val = "•" },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = "420", Hanging = "360" }
						}
					}
				) { AbstractNumberId = absNumIdRef + 1 },
				new AbstractNum(
					new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
					new Level {
						NumberingFormat = new NumberingFormat() { Val = NumberFormatValues.Bullet },
						LevelIndex = 0,
						LevelText = new LevelText() { Val = "▪" },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = "420", Hanging = "360" }
						}
					}
				) { AbstractNumberId = absNumIdRef + 2 },
				new AbstractNum(
					new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
					new Level {
						NumberingFormat = new NumberingFormat() { Val = NumberFormatValues.Bullet },
						LevelIndex = 0,
						LevelText = new LevelText() { Val = "o" },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = "420", Hanging = "360" }
						}
					}
				) { AbstractNumberId = absNumIdRef + 3 },
				new AbstractNum(
					new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
					new Level {
						StartNumberingValue = new StartNumberingValue() { Val = 1 },
						NumberingFormat = new NumberingFormat() { Val = NumberFormatValues.UpperLetter },
						LevelIndex = 0,
						LevelText = new LevelText() { Val = "%1." },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = "420", Hanging = "360" }
						}
					}
				) { AbstractNumberId = absNumIdRef + 4 },
				new AbstractNum(
					new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
					new Level {
						StartNumberingValue = new StartNumberingValue() { Val = 1 },
						NumberingFormat = new NumberingFormat() { Val = NumberFormatValues.LowerLetter },
						LevelIndex = 0,
						LevelText = new LevelText() { Val = "%1." },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = "420", Hanging = "360" }
						}
					}
				) { AbstractNumberId = absNumIdRef + 5 },
				new AbstractNum(
					new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
					new Level {
						StartNumberingValue = new StartNumberingValue() { Val = 1 },
						NumberingFormat = new NumberingFormat() { Val = NumberFormatValues.UpperRoman },
						LevelIndex = 0,
						LevelText = new LevelText() { Val = "%1." },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = "420", Hanging = "360" }
						}
					}
				) { AbstractNumberId = absNumIdRef + 6 },
				new AbstractNum(
					new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
					new Level {
						StartNumberingValue = new StartNumberingValue() { Val = 1 },
						NumberingFormat = new NumberingFormat() { Val = NumberFormatValues.LowerRoman },
						LevelIndex = 0,
						LevelText = new LevelText() { Val = "%1." },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = "420", Hanging = "360" }
						}
					}
				) { AbstractNumberId = absNumIdRef + 7 }
			};

			// this is not documented but MS Word needs that all the AbstractNum are stored consecutively.
			// Otherwise, it will apply the "NoList" style to the existing ListInstances.
			// This is the reason why I insert all the items after the last AbstractNum.
			int lastAbsNumIndex = 0;
			if (absNumIdRef > 0)
			{
				lastAbsNumIndex = numberingPart.Numbering.ChildElements.Count-1;
				for (; lastAbsNumIndex >= 0; lastAbsNumIndex--)
				{
					if(numberingPart.Numbering.ChildElements[lastAbsNumIndex] is AbstractNum)
						break;
				}
			}

			for (int i = 0; i < absNumChildren.Length; i++)
				numberingPart.Numbering.InsertAt(absNumChildren[i], i + lastAbsNumIndex);

			// initializes the lookup
			knonwAbsNumIds = new Dictionary<String, Int32>() {
				{ "disc", absNumIdRef+1 }, { "square", absNumIdRef+2 }, { "circle" , absNumIdRef+3 },
				{ "upper-alpha", absNumIdRef+4 }, { "lower-alpha", absNumIdRef+5 },
				{ "upper-roman", absNumIdRef+6 }, { "lower-roman", absNumIdRef+7 },
				{ "decimal", absNumIdRef }
			};

			// compute the next list instance ID seed. We start at 1 because 0 has a special meaning: 
			// The w:numId can contain a value of 0, which is a special value that indicates that numbering was removed
			// at this level of the style hierarchy. While processing this markup, if the w:val='0',
			// the paragraph does not have a list item (http://msdn.microsoft.com/en-us/library/ee922775(office.14).aspx)
			nextInstanceID = 1;
			foreach (NumberingInstance inst in numberingPart.Numbering.Elements<NumberingInstance>())
			{
				if (inst.NumberID.Value > nextInstanceID) nextInstanceID = inst.NumberID;
			}
			numInstances.Push(new KeyValuePair<int, int>(nextInstanceID, -1));

			numberingPart.Numbering.Save();
		}

		#endregion

		#region BeginList

		public void BeginList(HtmlEnumerator en)
		{
			int prevAbsNumId = numInstances.Peek().Value;
			var absNumId = -1;

			// lookup for a predefined list style in the template collection
			String type = en.StyleAttributes["list-style-type"];
			bool orderedList = en.CurrentTag.Equals("<ol>", StringComparison.OrdinalIgnoreCase);
			if (type == null || !knonwAbsNumIds.TryGetValue(type.ToLowerInvariant(), out absNumId))
			{
				if (orderedList)
					absNumId = knonwAbsNumIds["decimal"];
				else
					absNumId = knonwAbsNumIds["disc"];
			}

			firstItem = true;
			levelDepth++;
            if (levelDepth > maxlevelDepth)
            {
                maxlevelDepth = levelDepth;
            }

            // save a NumberingInstance if the nested list style is the same as its ancestor.
            // this allows us to nest <ol> and restart the indentation to 1.
            int currentInstanceId = this.InstanceID;
            if (levelDepth > 1 && absNumId == prevAbsNumId && orderedList)
            {
                EnsureMultilevel(absNumId);
            }
            else
            {
                // For unordered lists (<ul>), create only one NumberingInstance per level
                // (MS Word does not tolerate hundreds of identical NumberingInstances)
                if (orderedList || (levelDepth >= maxlevelDepth))
                {
                    currentInstanceId = ++nextInstanceID;
                    Numbering numbering = mainPart.NumberingDefinitionsPart.Numbering;
                    numbering.Append(
                        new NumberingInstance(
                            new AbstractNumId() { Val = absNumId },
                            new LevelOverride(
                                new StartOverrideNumberingValue() { Val = 1 }
                            )
                            { LevelIndex = 0, }
                        )
                        { NumberID = currentInstanceId });
                }
            }

			numInstances.Push(new KeyValuePair<int, int>(currentInstanceId, absNumId));
		}

		#endregion

		#region EndList

		public void EndList()
		{
			if (levelDepth > 0)
				numInstances.Pop();  // decrement for nested list
			levelDepth--;
			firstItem = true;
		}

		#endregion

		#region ProcessItem

		public int ProcessItem(HtmlEnumerator en)
		{
			if (!firstItem) return this.InstanceID;

			firstItem = false;

			// in case a margin has been specifically specified, we need to create a new list template
			// on the fly with a different AbsNumId, in order to let Word doesn't merge the style with its predecessor.
			Margin margin = en.StyleAttributes.GetAsMargin("margin");
			if (margin.Left.Value > 0 && margin.Left.Type == UnitMetric.Pixel)
			{
				Numbering numbering = mainPart.NumberingDefinitionsPart.Numbering;
				foreach (AbstractNum absNum in numbering.Elements<AbstractNum>())
				{
					if (absNum.AbstractNumberId == numInstances.Peek().Value)
					{
						Level lvl = absNum.GetFirstChild<Level>();
						Int32 currentNumId = ++nextInstanceID;

						numbering.Append(
							new AbstractNum(
									new MultiLevelType() { Val = MultiLevelValues.SingleLevel },
									new Level {
										StartNumberingValue = new StartNumberingValue() { Val = 1 },
										NumberingFormat = new NumberingFormat() { Val = lvl.NumberingFormat.Val },
										LevelIndex = 0,
										LevelText = new LevelText() { Val = lvl.LevelText.Val }
									}
								) { AbstractNumberId = currentNumId });
						numbering.Save(mainPart.NumberingDefinitionsPart);
						numbering.Append(
							new NumberingInstance(
									new AbstractNumId() { Val = currentNumId }
								) { NumberID = currentNumId });
						numbering.Save(mainPart.NumberingDefinitionsPart);
						mainPart.NumberingDefinitionsPart.Numbering.Reload();
						break;
					}
				}
			}

			return this.InstanceID;
		}

		#endregion

		#region EnsureMultilevel

		/// <summary>
		/// Find a specified AbstractNum by its ID and update its definition to make it multi-level.
		/// </summary>
		private void EnsureMultilevel(int absNumId)
		{
			AbstractNum absNumMultilevel = null;
			foreach (AbstractNum absNum in mainPart.NumberingDefinitionsPart.Numbering.Elements<AbstractNum>())
			{
				if (absNum.AbstractNumberId == absNumId)
				{
					absNumMultilevel = absNum;
					break;
				}
			}


			if (absNumMultilevel != null && absNumMultilevel.MultiLevelType.Val == MultiLevelValues.SingleLevel)
			{
				Level level1 = absNumMultilevel.GetFirstChild<Level>();
				absNumMultilevel.MultiLevelType.Val = MultiLevelValues.Multilevel;

				// skip the first level, starts to 2
				for (int i = 2; i < 10; i++)
				{
					absNumMultilevel.Append(new Level {
						StartNumberingValue = new StartNumberingValue() { Val = 1 },
						NumberingFormat = new NumberingFormat() { Val = level1.NumberingFormat.Val },
						LevelIndex = i - 1,
						LevelText = new LevelText() { Val = "%" + i + "." },
						PreviousParagraphProperties = new PreviousParagraphProperties {
							Indentation = new Indentation() { Left = (720 * i).ToString(CultureInfo.InvariantCulture), Hanging = "360" }
						}
					});
				}
			}
		}


        public void AddItem(Action<IParagraphBuilder> action)
        {
            var paragraph = new Paragraph
            {
                ParagraphProperties = new ParagraphProperties
                {
                    NumberingProperties = new NumberingProperties(new List<OpenXmlElement>
                    {
                        new NumberingLevelReference {Val = 0},
                        new NumberingId {Val = NumId}
                    })
                }
            };
            var paragraphBuilder = new ParagraphBuilder(paragraph);
            action(paragraphBuilder);
            _items.Add(paragraphBuilder.Build());
        }

        public void AddItem(string item)
        {
            AddItem(new TextElement(item));
        }


        public void AddItem(TextElement item)
        {
            var paragraph = new Paragraph
            {
                ParagraphProperties = new ParagraphProperties
                {
                    NumberingProperties = new NumberingProperties(new List<OpenXmlElement>
                    {
                        new NumberingLevelReference {Val = 0},
                        new NumberingId {Val = NumId}
                    })
                }
            };
            var paragraphBuilder = new ParagraphBuilder(paragraph);
            paragraphBuilder.AddText(item);
            _items.Add(paragraphBuilder.Build());
        }

        public void AddItem(TextElement[] elements)
        {
            var paragraph = new Paragraph
            {
                ParagraphProperties = new ParagraphProperties
                {
                    NumberingProperties = new NumberingProperties(new List<OpenXmlElement>
                    {
                        new NumberingLevelReference {Val = 0},
                        new NumberingId {Val = NumId}
                    })
                }
            };
            var paragraphBuilder = new ParagraphBuilder(paragraph);
            paragraphBuilder.AddText(elements);
            _items.Add(paragraphBuilder.Build());
        }

        protected void AddNumberingDefinitions(AbstractNum abstractNum, NumberingInstance numberingInstance)
        {
            var numberingDefinitionCount = NumberingDefinitionsPart.Numbering.Descendants<AbstractNum>().Count();

            if (numberingDefinitionCount > 0)
            {
                var lastAbstract = NumberingDefinitionsPart.Numbering.Descendants<AbstractNum>().Last();
                NumberingDefinitionsPart.Numbering.InsertAfter(abstractNum, lastAbstract);

                var lastNumberingInstance = NumberingDefinitionsPart.Numbering.Descendants<NumberingInstance>().Last();
                NumberingDefinitionsPart.Numbering.InsertAfter(numberingInstance, lastNumberingInstance);
            }
            else
            {
                NumberingDefinitionsPart.Numbering.AppendChild(abstractNum);
                NumberingDefinitionsPart.Numbering.AppendChild(numberingInstance);
            }
        }

        public List<Paragraph> Build()
        {
            return _items;
        }

using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DocxToTxt.NumberingUtils
{
    public class NumberingInfo
    {
        public AbstractNum AbstractNum { get; set; }
        public NumberingInstance NumberingInstance { get; set; }
        public List<Level> Levels { get; set; } = new List<Level>();



        public NumberingInfo() { }
    }
}


        public void AddItem(Action<IParagraphBuilder> action)
        {
            var paragraph = new Paragraph
            {
                ParagraphProperties = new ParagraphProperties
                {
                    NumberingProperties = new NumberingProperties(new List<OpenXmlElement>
                    {
                        new NumberingLevelReference {Val = 0},
                        new NumberingId {Val = NumId}
                    })
                }
            };
            var paragraphBuilder = new ParagraphBuilder(paragraph);
            action(paragraphBuilder);
            _items.Add(paragraphBuilder.Build());
        }

        public void AddItem(string item)
        {
            AddItem(new TextElement(item));
        }


        public void AddItem(TextElement item)
        {
            var paragraph = new Paragraph
            {
                ParagraphProperties = new ParagraphProperties
                {
                    NumberingProperties = new NumberingProperties(new List<OpenXmlElement>
                    {
                        new NumberingLevelReference {Val = 0},
                        new NumberingId {Val = NumId}
                    })
                }
            };
            var paragraphBuilder = new ParagraphBuilder(paragraph);
            paragraphBuilder.AddText(item);
            _items.Add(paragraphBuilder.Build());
        }

        public void AddItem(TextElement[] elements)
        {
            var paragraph = new Paragraph
            {
                ParagraphProperties = new ParagraphProperties
                {
                    NumberingProperties = new NumberingProperties(new List<OpenXmlElement>
                    {
                        new NumberingLevelReference {Val = 0},
                        new NumberingId {Val = NumId}
                    })
                }
            };
            var paragraphBuilder = new ParagraphBuilder(paragraph);
            paragraphBuilder.AddText(elements);
            _items.Add(paragraphBuilder.Build());
        }

        protected void AddNumberingDefinitions(AbstractNum abstractNum, NumberingInstance numberingInstance)
        {
            var numberingDefinitionCount = NumberingDefinitionsPart.Numbering.Descendants<AbstractNum>().Count();

            if (numberingDefinitionCount > 0)
            {
                var lastAbstract = NumberingDefinitionsPart.Numbering.Descendants<AbstractNum>().Last();
                NumberingDefinitionsPart.Numbering.InsertAfter(abstractNum, lastAbstract);

                var lastNumberingInstance = NumberingDefinitionsPart.Numbering.Descendants<NumberingInstance>().Last();
                NumberingDefinitionsPart.Numbering.InsertAfter(numberingInstance, lastNumberingInstance);
            }
            else
            {
                NumberingDefinitionsPart.Numbering.AppendChild(abstractNum);
                NumberingDefinitionsPart.Numbering.AppendChild(numberingInstance);
            }
        }

        public List<Paragraph> Build()
        {
            return _items;
        }

DocumentFormat.OpenXml.Wordprocessing.NumberingInstance : IEnumerable

Constructors :

public NumberingInstance()
public NumberingInstance(IEnumerable<OpenXmlElement> childElements = )
public NumberingInstance(OpenXmlElement[] childElements = )
public NumberingInstance(String outerXml = )

Methods :

public Int32Value get_NumberID()
public Void set_NumberID(Int32Value value = )
public AbstractNumId get_AbstractNumId()
public Void set_AbstractNumId(AbstractNumId value = )
public OpenXmlElement CloneNode(Boolean deep = )
public OpenXmlElement get_FirstChild()
public OpenXmlElement get_LastChild()
public Boolean get_HasChildren()
public String get_InnerText()
public Void set_InnerXml(String value = )
public Boolean AddChild(OpenXmlElement newChild = , Boolean throwOnError = True)
public T AppendChild(T newChild = )
public T InsertAfter(T newChild = , OpenXmlElement referenceChild = )
public T InsertBefore(T newChild = , OpenXmlElement referenceChild = )
public T InsertAt(T newChild = , Int32 index = )
public T PrependChild(T newChild = )
public T RemoveChild(T child = )
public Void RemoveAllChildren()
public T ReplaceChild(OpenXmlElement newChild = , T oldChild = )
public Void RemoveAllChildren()
public Void Remove()
public Boolean IsAfter(OpenXmlElement element = )
public Boolean IsBefore(OpenXmlElement element = )
public Void AddAnnotation(Object annotation = )
public T Annotation()
public Object Annotation(Type type = )
public IEnumerable<T> Annotations()
public IEnumerable<Object> Annotations(Type type = )
public Void RemoveAnnotations()
public Void RemoveAnnotations(Type type = )
public IEnumerator<OpenXmlElement> GetEnumerator()
public Object Clone()
public MarkupCompatibilityAttributes get_MCAttributes()
public Void set_MCAttributes(MarkupCompatibilityAttributes value = )
public String LookupNamespace(String prefix = )
public String LookupPrefix(String namespaceUri = )
public IFeatureCollection get_Features()
public OpenXmlElementContext get_OpenXmlElementContext()
public Boolean get_HasAttributes()
public IEnumerable<OpenXmlAttribute> get_ExtendedAttributes()
public OpenXmlElementList get_ChildElements()
public OpenXmlElement get_Parent()
public String get_NamespaceUri()
public String get_LocalName()
public String get_Prefix()
public IEnumerable<KeyValuePair<StringString>> get_NamespaceDeclarations()
public XmlQualifiedName get_XmlQualifiedName()
public XName get_XName()
public String get_InnerXml()
public String get_OuterXml()
public OpenXmlAttribute GetAttribute(String localName = , String namespaceUri = )
public IList<OpenXmlAttribute> GetAttributes()
public Void SetAttribute(OpenXmlAttribute openXmlAttribute = )
public Void RemoveAttribute(String localName = , String namespaceUri = )
public Void SetAttributes(IEnumerable<OpenXmlAttribute> openXmlAttributes = )
public Void ClearAllAttributes()
public Void AddNamespaceDeclaration(String prefix = , String uri = )
public Void RemoveNamespaceDeclaration(String prefix = )
public T GetFirstChild()
public OpenXmlElement PreviousSibling()
public T PreviousSibling()
public OpenXmlElement NextSibling()
public T NextSibling()
public IEnumerable<OpenXmlElement> Ancestors()
public IEnumerable<T> Ancestors()
public IEnumerable<T> Elements()
public IEnumerable<OpenXmlElement> Elements()
public IEnumerable<T> Descendants()
public IEnumerable<OpenXmlElement> Descendants()
public IEnumerable<OpenXmlElement> ElementsBefore()
public IEnumerable<OpenXmlElement> ElementsAfter()
public Void WriteTo(XmlWriter xmlWriter = )
public Void Append(IEnumerable<OpenXmlElement> newChildren = )
public Void Append(OpenXmlElement[] newChildren = )
public T InsertAfterSelf(T newElement = )
public T InsertBeforeSelf(T newElement = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods