PDFsharp & MigraDoc Foundation

Working with link annotations
Page 1 of 1

Author:  sgagnon [ Tue Apr 18, 2017 7:46 pm ]
Post subject:  Working with link annotations

Hey everyone,

My latest project involves some post-processing of some generated PDFs. I have a third-party program that generates PDFs for us. The problem is that the links in the PDFs are created as web links, instead of file links.

Due to the security of some of our client networks, the web links are sometimes being blocked. I've been tasked with changing all of the web links to file links (we have confirmed that file links with the same URLs work).

After a little poking around, I was able to create the following method.

        public static void ConvertWebLinksToFileLinks(string filePath)
            using (PdfDocument doc = PdfReader.Open(filePath))
                foreach (PdfPage page in doc.Pages)

                    //create a list of web links
                    List<PdfAnnotation> toBeChanged = new List<PdfAnnotation>();
                    foreach (PdfAnnotation a in page.Annotations)
                        if (a.Elements.GetString(PdfAnnotation.Keys.Subtype) == "/Link")
                            string uri = a.Elements.GetDictionary(PdfAnnotation.Keys.A)?.Elements.GetString(@"/URI");

                            if (!String.IsNullOrWhiteSpace(uri))


                    //for each web link, create a file link on top of it
                    foreach (var i in toBeChanged)
                        string uri = i.Elements.GetDictionary(PdfAnnotation.Keys.A).Elements.GetString("/URI");
                        page.AddFileLink(i.Rectangle, uri);


This works perfectly, and we've confirmed that the resulting documents work on our client's networks. The only thing is that it is essentially creating a second link that covers the original link. This isn't too bad, but I would prefer to delete the original once I've created the new one.

The problem is that I can't figure out how to delete the original. I've tried the following:

- PdfAnnotation.Delete(); // this doesn't work, it's flagged as obsolete, and I'm told to use parent.Remove(this);
- page.Annotations.Remove(PdfAnnotation); // this doesn't work, I get the following exception: "Only indirect objects can be removed."
- page.Annotations.Clear(); // tried this, as the only annotations in my files are web links. It also failed with the same exception: "Only indirect objects can be removed."

I am using the GDI build of PDFSharp, NuGet version 1.32.2602

What I have works, but I hate having the double links. I would definitely appreciate any help that anyone could offer.



Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group