1

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

keithl8041
  • 2,383
  • 20
  • 27

1 Answers1

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.

keithl8041
  • 2,383
  • 20
  • 27
  • To help make things clear. The parameters being passed are "The original Page", The New Document, and the position of the page in the new document. But this is an excellent fix to this problem. – KeithL Jul 12 '22 at 15:14
  • I am a little unclear why the for loop with the p exists and not just target doc.Pages[docPage] – KeithL Jul 12 '22 at 15:15
  • Hmm yeah it's unclear to me as well. Perhaps it was intended to be `doc.Pages[p].Annotations.Add(PdfLinkAnnotation.CreateWebLink(rect, uri));`. – keithl8041 Jul 13 '22 at 08:56