Flayms/Markdown2Pdf

The TOC have an unordered list item page

ABatenev opened this issue · 1 comments

If I have an unordered list in the md file and it is followed by headers with the same names, then TOC takes the pages of the list, not the header. For example:
Test.md
Test.pdf

The current code to detect the page numbers is really simple (and also inefficient), it creates the PDF, then searches for the names of the headers and saves the page numbers it finds:

private void _ReadPageNumbers(object _, PdfArgs e) { // TODO: what if link not found
if (this._links == null)
throw new InvalidOperationException("Links have not been created yet.");
using var pdf = PdfDocument.Open(e.PdfPath);
this._linkPages = _ParsePageNumbersFromPdf(pdf, this._links).ToArray();
// Fill in values that could not be found
var length = this._links.Length;
for (var i = 0; i < length; ++i) {
if (this._linkPages[i] != null)
continue;
this._linkPages[i] = i == 0
? new(this._links[i], 1) // Assume first page
: new(this._links[i], this._linkPages[i - 1].PageNumber); // Assume same as previous
}
}
private static IEnumerable<LinkWithPageNumber> _ParsePageNumbersFromPdf(PdfDocument pdf, Link[] links) {
var linkPages = new LinkWithPageNumber[links.Count()];
var linksToFind = links.ToList();
foreach (var page in pdf.GetPages()) {
var text = ContentOrderTextExtractor.GetText(page);
var lines = _lineBreakRegex.Split(text);
foreach (var line in lines)
foreach (var link in linksToFind) {
if (link.Title != line)
continue;
linkPages[Array.IndexOf(links, link)] = new(link, page.Number);
linksToFind.Remove(link);
if (linksToFind.Count() == 0)
return linkPages; // All links found
break; // Found link, continue with next line
}
}
return linkPages;
}

This obviously causes issues when the header names exist somewhere else in the PDF.
I don't see an easy way to resolve this though, PDF analysis is quite difficult. It's difficult to know what on a page is a header or to which page a link is pointing.

I am open for ideas or PRs on a better way of handling this.