tableOfContents = [];
using (PdfDocument pdfDocument = PdfDocument.Open(pdfPath))
{
foreach (Page page in pdfDocument.GetPages())
{
cancellationToken.ThrowIfCancellationRequested();
if (page.Number > MAX_PAGES)
break;
// The location reference of a page is its 1-based page number (PdfPig pages are numbered from 1), which is the only stable identifier a PDF page has, and it doubles as the name of the section file.
string locationRef = $"page:{page.Number}";
string fileName = $"{page.Number}.html";
string pageHtml = BuildPageHtml(page);
// A page may have no text at all, in which case the HTML is only the empty section wrapper; the text-content
// detection looks at the paragraphs actually produced, because the wrapper is always present.
if (pageHtml.Contains(""))
hasTextContent = true;
File.WriteAllText(Path.Combine(sectionsDirectory, fileName), pageHtml, Encoding.UTF8);
spine.Add(new ReadingSpineItemDto(locationRef, null, $"sections/{fileName}"));
}
// The table of contents is read from the document that was already opened for the pages, so the PDF is not opened twice.
tableOfContents = ReadTableOfContents(pdfDocument);
}
// The author and the cover are not extracted in this text-only iteration, and a PDF has no embedded resources to serve, so the resources dictionary is empty.
return new ReadingDocumentDto(Path.GetFileNameWithoutExtension(pdfPath), null, null, tableOfContents, spine, new Dictionary(), hasTextContent);
}
///
/// Builds the HTML content of a PDF page, wrapping its extracted text into paragraphs.
///
/// The PDF page whose content is built.
/// The HTML content of the PDF page.
private static string BuildPageHtml(Page page)
{
// The extracted text comes from the untrusted document, so each line is HTML-encoded before it is wrapped, keeping any embedded markup inert until the host sanitizes the whole section anyway;
// the lines are wrapped in paragraphs so that the page reads like a document, instead of one unbroken wall of text.
StringBuilder stringBuilder = new();
stringBuilder.Append("");
string text = page.Text ?? string.Empty;
foreach (string line in text.Replace("\r\n", "\n").Split('\n'))
{
if (string.IsNullOrWhiteSpace(line))
continue;
stringBuilder.Append("").Append(WebUtility.HtmlEncode(line)).Append("
");
}
stringBuilder.Append("");
return stringBuilder.ToString();
}
///
/// Reads the table of contents of the PDF from the bookmarks of the already open document.
///
/// The open PDF document whose bookmarks are read.
/// The table of contents of the PDF, or an empty list when the PDF has no usable bookmarks.
private static List ReadTableOfContents(PdfDocument pdfDocument)
{
try
{
// Many PDFs have no bookmarks at all (for example a book exported from a word processor), in which case the reader simply shows no table of contents instead of failing the whole book.
if (!pdfDocument.TryGetBookmarks(out Bookmarks? bookmarks) || bookmarks is null || bookmarks.Roots.Count == 0)
return [];
return [.. bookmarks.Roots.Select(ToTocEntry)];
}
catch (OperationCanceledException)
{
// A cancelled parse must not silently succeed with an empty table of contents, so the cancellation is rethrown instead of
// being swallowed: the request was aborted, not the bookmarks found unreadable.
throw;
}
catch (Exception)
{
// The bookmarks of a malformed PDF are best effort, so the table of contents is skipped instead of failing the book; the pages themselves are still readable.
return [];
}
}
///
/// Converts a bookmark of the PDF into a table of contents entry.
///
/// The bookmark to convert.
/// The converted table of contents entry.
private static ReadingTocEntryDto ToTocEntry(BookmarkNode bookmark)
{
// Only a document bookmark has a destination page; the other bookmark kinds (external, embedded, URI) cannot be navigated inside the reader, so they yield an entry that points nowhere,
// and the client simply does not render it as navigable.
int? pageNumber = bookmark is DocumentBookmarkNode documentBookmark ? documentBookmark.PageNumber : null;
string locationRef = pageNumber is null ? string.Empty : $"page:{pageNumber.Value}";
// The nested bookmarks of a bookmark become the children of the entry, preserving the hierarchy of the outline.
List children = [.. bookmark.Children.Select(ToTocEntry)];
return new ReadingTocEntryDto(bookmark.Title ?? string.Empty, locationRef, children);
}
}