RedactLinks.vb
C# VB
'''' This code is part of Document Solutions for PDF .NET demos.'' Copyright (c) MESCIUS inc. All rights reserved.''Imports System.IOImports System.DrawingImports System.LinqImports System.Collections.GenericImports GrapeCity.Documents.PdfImports GrapeCity.Documents.Pdf.AnnotationsImports GrapeCity.Documents.Pdf.Actions
'' This sample shows how to find and remove all links to a certain URL from a PDF.'' The code first finds all link annotations with ActionURI pointing to the URL'' that needs to be removed, then uses redact to erase all content within the found link areas.'' Red overlay is used by the redacts to visualize the erased areas.'''' The PDF used by this sample, but with links intact, can be seen in the FindAndHighlight sample.Public Class RedactLinks Public Function CreatePDF(ByVal stream As Stream) As Integer '' Load the PDF with links that need to be removed: Dim doc = New GcPdfDocument() Using fs = File.OpenRead(Path.Combine("Resources", "PDFs", "fendo-13-1005722.pdf")) doc.Load(fs)
'' Remove all links containing this string: Const targetUrl = "frontiersin.org"
'' Find all relevant link annotations: Dim linkAnnotations = New HashSet(Of LinkAnnotation)() For Each page In doc.Pages For Each a In page.Annotations If TypeOf a Is LinkAnnotation Then Dim la = DirectCast(a, LinkAnnotation) If TypeOf la.Action Is ActionURI Then Dim actUri = DirectCast(la.Action, ActionURI) If Not String.IsNullOrEmpty(actUri.URI) AndAlso actUri.URI.Contains(targetUrl) Then linkAnnotations.Add(la) End If End If End If Next Next '' Loop through the found links, add redact annotations for each: For Each la In linkAnnotations For Each page In la.Pages ' We must make a copy of page.Annotations to be able to add redact annotations in a foreach loop: Dim annots = page.Annotations.Where(Function(a_) a_ Is la).ToList() For Each a In annots page.Annotations.Add(New RedactAnnotation() With { .Rect = la.Rect, .OverlayFillColor = Color.Red }) Next Next Next '' Apply the redacts: doc.Redact()
'' Done: doc.Save(stream) Return doc.Pages.Count End Using End FunctionEnd Class