PDFsharp & MigraDoc Foundation
https://forum.pdfsharp.net/

Fixing document bookmarks on merge.
https://forum.pdfsharp.net/viewtopic.php?f=2&t=3559
Page 1 of 1

Author:  grip [ Fri Mar 24, 2017 5:10 pm ]
Post subject:  Fixing document bookmarks on merge.

Hi all,
I'm a newbie with this library. It's pretty nice and very fast so I'm happy with that. I've been trying to fix bookmarks on merged documents. I found this code snippet someone had previous uploaded.

static void FixLinkAnnotations(PdfPage page, PdfDocument doc, int pageOffset)
{
for (var i = 0; i < page.Annotations.Count; i++)
{
var annot = page.Annotations[i];
var subType = annot.Elements.GetString(PdfAnnotation.Keys.Subtype);
if (subType == "/Link")
{
var dest = annot.Elements.GetArray("/Dest"); // may also be a named destination
var rect = annot.Elements.GetRectangle(PdfAnnotation.Keys.Rect);
if (dest != null && rect != null && dest.Elements.Count > 0)
{
var targetPage = dest.Elements.GetReference(0);
for (var p = 0; p < doc.PageCount; p++)
{
if (doc.Pages[p].Reference == targetPage)
{
page.Annotations.Elements[i] = PdfLinkAnnotation.CreateDocumentLink(rect, p + pageOffset);
// TODO: copy additional properties from original annotation ?
}
}
}
}
}
}

It looks good but my code always returns a null for the line:
var dest = annot.Elements.GetArray("/Dest");

I've done a watch on the PdfAnnotion object and that key is missing in the Elements array. The bookmark works fine in the original document and behaves just like bookmarks I've added with PdfLinkAnnotation.CreateDocumentLink(bookmarkRect, PageNumber).

I've tried casting the PdfAnnotion to a PdfLinkAnnotation since the Subtype = "/Link" but that just gets me this error:
"Unable to cast object of type 'PdfSharp.Pdf.Annotations.PdfGenericAnnotation' to type 'PdfSharp.Pdf.Annotations.PdfLinkAnnotation'."
I noticed that the PdfLinkAnnotation object has a DestPage property so I thought that might work.

One other thing I did try was to try to import the annotations from the original document into the new merged document. Even after cloning the annotation I would get a duplicate key error. If anyone could tell me how to get around this, I'd appreciate it.

I've pretty much run out of ideas so I'm posting this here in the hopes someone can give me a clue.
Thanks,
Alan

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/