Merge pull request #473 from grinay/master

Fix page number order.
This commit is contained in:
Eliot Jones 2022-08-13 16:02:44 -04:00 committed by GitHub
commit 2f9a9ace9a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 55 additions and 3 deletions

View File

@ -32,7 +32,7 @@
/// <summary>
/// The number of this page if <see cref="IsPage"/> is <see langword="true"/>.
/// </summary>
public int? PageNumber { get; }
public int? PageNumber { get; internal set; }
/// <summary>
/// The child nodes of this node if <see cref="IsPage"/> is <see langword="false" />

View File

@ -5,8 +5,10 @@
using Content;
using Core;
using Parts;
using System.Linq;
using Tokenization.Scanner;
using Tokens;
using Util;
internal static class CatalogFactory
{
@ -80,6 +82,8 @@
return new PageTreeNode(nodeDictionaryInput, referenceInput, true, pageNumber.PageCount).WithChildren(EmptyArray<PageTreeNode>.Instance);
}
//If we got here, we have to iterate till we manage to exit
@ -126,8 +130,6 @@
if (isChildPage)
{
pageNumber.Increment();
var kidPageNode =
new PageTreeNode(kidDictionaryToken, kidRef.Data, true, pageNumber.PageCount).WithChildren(EmptyArray<PageTreeNode>.Instance);
current.nodeChildren.Add(kidPageNode);
@ -152,6 +154,12 @@
action();
}
foreach (var child in firstPage.Children.ToRecursiveOrderList(x=>x.Children).Where(child => child.IsPage))
{
pageNumber.Increment();
child.PageNumber = pageNumber.PageCount;
}
return firstPage;
}

View File

@ -0,0 +1,44 @@
namespace UglyToad.PdfPig.Util
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
internal static class EnumerableExtensions
{
public static List<T> ToRecursiveOrderList<T>(this IEnumerable<T> collection,
Expression<Func<T, IEnumerable<T>>> childCollection)
{
var resultList = new List<T>();
var currentItems = new Queue<(int Index, T Item, int Depth)>(collection.Select(i => (0, i, 0)));
var depthItemCounter = 0;
var previousItemDepth = 0;
var childProperty = (PropertyInfo)((MemberExpression)childCollection.Body).Member;
while (currentItems.Count > 0)
{
var currentItem = currentItems.Dequeue();
// Reset counter for number of items at this depth when the depth changes.
if (currentItem.Depth != previousItemDepth)
{
depthItemCounter = 0;
}
var resultIndex = currentItem.Index + depthItemCounter++;
resultList.Insert(resultIndex, currentItem.Item);
var childItems = childProperty.GetValue(currentItem.Item) as IEnumerable<T> ?? Enumerable.Empty<T>();
foreach (var childItem in childItems)
{
currentItems.Enqueue((resultIndex + 1, childItem, currentItem.Depth + 1));
}
previousItemDepth = currentItem.Depth;
}
return resultList;
}
}
}