onizet / html2openxml

Html2OpenXml is a small .Net library that convert simple or advanced HTML to plain OpenXml components. This program has started in 2009, initially to convert user's comments from SharePoint to Word.
MIT License
297 stars 106 forks source link

Fix "range out value" on try insert number html list #132

Closed mldzs closed 5 months ago

mldzs commented 1 year ago

I was trying to use the most current version of the library and I came across an error in my project. I currently have a WORD Template already populated with some information, but none of it is an html list. Based on this template I try to write an html containing <ol> and <ul> (these examples available here in the repository). But I always get the following error: "Specified argument was out of the range of valid values. (Parameter 'index'). StackTrace:    at DocumentFormat.OpenXml.OpenXmlCompositeElement.InsertAt[T](T newChild, Int32 index)\r\n   at HtmlToOpenXml.NumberingListStyleCollection.InitNumberingIds() in C:\\Dev\\html2openxml-dev\\src\\Html2OpenXml\\Collections\\NumberingListStyleCollection.cs:line 219

After debugging, we found a possible cause, but we still don't quite understand why: image the value of lastAbsNumIndex is being -1. As i = 0 initially, an attempt is made to insert an object at index -1.

analyzing further, we can see that the error starts in this section, because it starts the "absNumIdRef" with 0, and then immediately checks: mainPart.NumberingDefinitionsPart.Numbering == null. However, Numbering is non-nullable, so it never enters this snippet. Furthermore, after passing the else, where there is no element in the numberingPart.Numbering.Elements() list, the for is not executed and absNumIdRef becomes 1. image

with "absNumIdRef" being 1, the clause "if (absNumIdRef > 0)" returns True and the code then executes. We have that "numberingPart.Numbering.ChildElements.Count" is equal to 0 in our document (from what we understand, it would be filled only if an html list element already exists, but we don't). The subtraction "lastAbsNumIndex = numberingPart.Numbering.ChildElements.Count-1;" makes "lastAbsNumIndex = -1", and then the "for" is not executed. After that, the code snippet is executed that tries to add the element at index -1. image

we don't know exactly if the solution makes sense with all the context of the library, but it worked for the scenario we had.