'Hyperlinks are lost when using PDFsharp to concatenate multiple PDFs

When using PDFsharp (v1.5x) to concatenate multiple PDF files, hyperlinks that exist in the source files are lost.



Solution 1:[1]

The links need to be manually recreated in the composite file. Run this method each time you add a new PdfPage object to the target document.

private void FixWebLinkAnnotations(PdfPage page, PdfDocument doc, int docPage)
{
    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.GetDictionary(PdfAnnotation.Keys.A);
            var rect = annot.Elements.GetRectangle(PdfAnnotation.Keys.Rect);
            if (dest != null && rect != null && dest.Elements.Count > 0)
            {
                var uri = dest.Elements.GetString("/URI");
                for (var p = 0; p < doc.PageCount; p++)
                {
                    if (p == docPage && uri != null)
                    {
                        doc.Pages[docPage].Annotations.Add(PdfLinkAnnotation.CreateWebLink(rect, uri));
                    }
                }
            }
        }
    }
}

This code was adapted from https://forum.pdfsharp.net/viewtopic.php?f=3&t=3382 to work with hyperlinks rather than document references.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 keithl8041