Can you please advise on how to merge the source document's outline into a
PdfDocument instance when consolidating multiple documents into a single one?
This example works fine until I attempt to add the
PdfOutline instance from the opened document to the
outputPdf's:
Code:
var documentPaths = new { "./A.pdf", "./B.pdf" };
var outputPdf = new PdfDocument();
var index = 0;
foreach (var currentPdf in documentPaths.Select(path => PdfReader.Open(path, PdfDocumentOpenMode.Import))) {
// This works.
outputPdf.Pages.InsertRange(index, currentPdf, AnnotationCopyingType.DeepCopy);
index += currentPdf.PageCount;
// This breaks because of an exception (see next block of code)
currentPdf.Outlines.ForEach(outline => outputPdf.Outlines.Add(outline));
}
The version of PdfSharp (PdfSharpCore) in use is 1.3.60.
Looks like the library is attempting to update the document on the
source outline while copying the object over to the
output outline. The exception message is the following:
Code:
System.InvalidOperationException: Cannot change document.
at PdfSharpCore.Pdf.PdfObject.set_Document(PdfDocument value)
at PdfSharpCore.Pdf.PdfOutlineCollection.AddToOutlinesTree(PdfOutline outline)
at PdfSharpCore.Pdf.PdfOutlineCollection.Add(PdfOutline outline)
The behavior is unexpected if not wrong, but I can see why the library code wants to set the a reference to the new document on the source outline.
As an alternative, I've tried creating and adding fresh
PdfOutline instances to the output document's outline. This works, but I'm now having a bit of trouble correlating this floating outline instance with the page it's meant to point to.
I can't correlate the new outline to a source document's page because
outline.DestinationPage is always NULL, so doing this doesn't work:
Code:
currentPdf.Outlines.ForEach(outline => outputPdf.Outlines.Add(outline.Title, outline.DestinationPage));
It seems to me that
DestinationPage is NULL because the original outline is
PdfPageDestinationType.Xyz, which is OK. I could work with that, but I need a little help.
Knowing that my
PdfOutline is
PdfPageDestinationType.Xyz, how can I get the outline's destination position and convert that into a reference to the page? Ideally in the
outputPdf, but even finding the destination in the original
PdfPage instance would work. I should be able to come up with that code myself.
Alternatively, are there any better, or more sensible approaches to merging a document's outline with another?