Skip to content

Commit 0f3b10c

Browse files
authored
Add basic support for link annotations (#93)
1 parent 3bfcebe commit 0f3b10c

5 files changed

Lines changed: 136 additions & 0 deletions

File tree

‎samples/Synercoding.FileFormats.Pdf.ConsoleTester/Program.cs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,25 @@ private static void _writePdf(string fileName, bool enableSubsetting = true)
248248

249249
page.Content.AddImage(forestImage, matrix);
250250
}
251+
})
252+
// Add hyperlink
253+
.AddPage(page =>
254+
{
255+
page.MediaBox = mediaBox;
256+
page.TrimBox = trimBox;
257+
258+
using (var forestStream = File.OpenRead("Pexels_com/android-wallpaper-art-backlit-1114897.jpg"))
259+
using (var forestImage = SixLabors.ImageSharp.Image.Load<Rgba32>(forestStream))
260+
{
261+
var scale = (double)forestImage.Width / forestImage.Height;
262+
263+
var matrix = Matrix.CreateScaleMatrix(new Value(scale * 303, Unit.Millimeters).AsRaw(Unit.Points), new Value(303, Unit.Millimeters).AsRaw(Unit.Points))
264+
.Translate(new Value(-100, Unit.Millimeters).AsRaw(Unit.Points), new Value(0, Unit.Millimeters).AsRaw(Unit.Points));
265+
266+
page.Content.AddImage(forestImage, matrix);
267+
268+
page.AddHyperlink(new Uri("https://www.github.com/synercoder/fileformats.pdf"), new Rectangle(new Point(Mm(-100), Mm(0)), new Size(scale * 303, 303, Unit.Millimeters)));
269+
}
251270
});
252271

253272
using (var blurStream = File.OpenRead("Pexels_com/4k-wallpaper-blur-bokeh-1484253.jpg"))

‎src/Synercoding.FileFormats.Pdf/Generation/WriteablePage.cs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ namespace Synercoding.FileFormats.Pdf.Generation;
1212
public class WriteablePage : IDisposable
1313
{
1414
private readonly TableBuilder _tableBuilder;
15+
private readonly List<PdfObject<PdfDictionary>> _annotations = [];
1516

1617
internal WriteablePage(TableBuilder tableBuilder, CachedResources cachedResources, int pageNumber)
1718
{
@@ -26,6 +27,9 @@ internal WriteablePage(TableBuilder tableBuilder, CachedResources cachedResource
2627

2728
internal PageResources Resources { get; }
2829

30+
internal IReadOnlyList<PdfObject<PdfDictionary>> Annotations
31+
=> _annotations;
32+
2933
/// <summary>
3034
/// The rotation of how the page is displayed, must be in increments of 90
3135
/// </summary>
@@ -77,6 +81,47 @@ public PageRotation? Rotation
7781
/// </summary>
7882
public IPageContentContext Content { get; }
7983

84+
/// <summary>
85+
/// Adds a clickable hyperlink annotation to the page that opens an external URI.
86+
/// </summary>
87+
/// <param name="uri">The absolute URI to open. Must be an absolute URI.</param>
88+
/// <param name="rectangle">
89+
/// The clickable area, expressed in default user space. This is <b>not</b> affected by any
90+
/// transformation applied through <see cref="Content"/>.
91+
/// </param>
92+
/// <returns>Returns this <see cref="WriteablePage"/> to chain calls.</returns>
93+
/// <exception cref="ArgumentNullException">Thrown when <paramref name="uri"/> is <see langword="null"/>.</exception>
94+
/// <exception cref="ArgumentException">Thrown when <paramref name="uri"/> is not an absolute URI.</exception>
95+
public WriteablePage AddHyperlink(Uri uri, Rectangle rectangle)
96+
{
97+
ArgumentNullException.ThrowIfNull(uri);
98+
if (!uri.IsAbsoluteUri)
99+
throw new ArgumentException("The provided uri must be an absolute uri.", nameof(uri));
100+
101+
var annotation = new PdfDictionary()
102+
{
103+
[PdfNames.Type] = PdfNames.Annot,
104+
[PdfNames.Subtype] = PdfNames.Link,
105+
[PdfNames.Rect] = rectangle.ToArray(),
106+
[PdfNames.Border] = new PdfArray(new[] { 0, 0, 0 }), // no visible border
107+
[PdfNames.F] = new PdfNumber(4), // Print flag
108+
[PdfNames.A] = new PdfDictionary()
109+
{
110+
[PdfNames.S] = PdfNames.URI,
111+
// Written as a hex string so characters like '(' ')' '\' in the uri can not corrupt the string literal.
112+
[PdfNames.URI] = new PdfString(System.Text.Encoding.ASCII.GetBytes(uri.AbsoluteUri), isHex: true),
113+
}
114+
};
115+
116+
_annotations.Add(new PdfObject<PdfDictionary>()
117+
{
118+
Id = _tableBuilder.ReserveId(),
119+
Value = annotation
120+
});
121+
122+
return this;
123+
}
124+
80125
internal PdfDictionary ToDictionary()
81126
{
82127
var dictionary = new PdfDictionary()
@@ -97,6 +142,8 @@ internal PdfDictionary ToDictionary()
97142
dictionary[PdfNames.ArtBox] = ArtBox.Value.ToArray();
98143
if (Rotation.HasValue)
99144
dictionary[PdfNames.Rotate] = new PdfNumber((int)Rotation.Value);
145+
if (_annotations.Count > 0)
146+
dictionary[PdfNames.Annots] = new PdfArray(_annotations.Select(a => a.Id.GetReference()).Cast<IPdfPrimitive>().ToArray());
100147

101148
return dictionary;
102149
}

‎src/Synercoding.FileFormats.Pdf/PdfWriter.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,10 @@ private void _processPage(WriteablePage page)
278278
Value = streamObj
279279
});
280280

281+
// Write annotations
282+
foreach (var annotation in page.Annotations)
283+
_objectWriter.Write(annotation);
284+
281285
_pages.Add(page.ToDictionary());
282286
}
283287

‎src/Synercoding.FileFormats.Pdf/Primitives/PdfNames.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ public static PdfName AESV2
1212
=> PdfName.Get(nameof(AESV2));
1313
public static PdfName AESV3
1414
=> PdfName.Get(nameof(AESV3));
15+
public static PdfName A
16+
=> PdfName.Get(nameof(A));
17+
public static PdfName Annot
18+
=> PdfName.Get(nameof(Annot));
19+
public static PdfName Annots
20+
=> PdfName.Get(nameof(Annots));
1521
public static PdfName ASCII85Decode
1622
=> PdfName.Get(nameof(ASCII85Decode));
1723
public static PdfName ASCIIHexDecode
@@ -32,6 +38,8 @@ public static PdfName BleedBox
3238
=> PdfName.Get(nameof(BleedBox));
3339
public static PdfName BM
3440
=> PdfName.Get(nameof(BM));
41+
public static PdfName Border
42+
=> PdfName.Get(nameof(Border));
3543
public static PdfName CA
3644
=> PdfName.Get(nameof(CA));
3745
public static PdfName ca
@@ -114,6 +122,8 @@ public static PdfName Exclusion
114122
=> PdfName.Get(nameof(Exclusion));
115123
public static PdfName ExtGState
116124
=> PdfName.Get(nameof(ExtGState));
125+
public static PdfName F
126+
=> PdfName.Get(nameof(F));
117127
public static PdfName Filter
118128
=> PdfName.Get(nameof(Filter));
119129
public static PdfName First
@@ -168,6 +178,8 @@ public static PdfName Length1
168178
=> PdfName.Get(nameof(Length1));
169179
public static PdfName Lighten
170180
=> PdfName.Get(nameof(Lighten));
181+
public static PdfName Link
182+
=> PdfName.Get(nameof(Link));
171183
public static PdfName Luminosity
172184
=> PdfName.Get(nameof(Luminosity));
173185
public static PdfName LZWDecode
@@ -232,6 +244,8 @@ public static PdfName Properties
232244
=> PdfName.Get(nameof(Properties));
233245
public static PdfName R
234246
=> PdfName.Get(nameof(R));
247+
public static PdfName Rect
248+
=> PdfName.Get(nameof(Rect));
235249
public static PdfName Registry
236250
=> PdfName.Get(nameof(Registry));
237251
public static PdfName Resources
@@ -242,6 +256,8 @@ public static PdfName Rotate
242256
=> PdfName.Get(nameof(Rotate));
243257
public static PdfName RunLengthDecode
244258
=> PdfName.Get(nameof(RunLengthDecode));
259+
public static PdfName S
260+
=> PdfName.Get(nameof(S));
245261
public static PdfName Saturation
246262
=> PdfName.Get(nameof(Saturation));
247263
public static PdfName Screen
@@ -298,6 +314,8 @@ public static PdfName U
298314
=> PdfName.Get(nameof(U));
299315
public static PdfName UE
300316
=> PdfName.Get(nameof(UE));
317+
public static PdfName URI
318+
=> PdfName.Get(nameof(URI));
301319
public static PdfName UseAttachments
302320
=> PdfName.Get(nameof(UseAttachments));
303321
public static PdfName UseNone

‎tests/Synercoding.FileFormats.Pdf.Tests/PdfWriterTests.cs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,4 +230,52 @@ public void Test_PdfWriter_WithOnlyPageLayout_WritesOnlyPageLayout()
230230
Assert.DoesNotContain("/PageMode", pdfContent);
231231
Assert.Contains("/PageLayout/TwoPageRight", pdfContent);
232232
}
233+
234+
[Fact]
235+
public void Test_PdfWriter_AddHyperlink_WritesLinkAnnotation()
236+
{
237+
// Arrange
238+
using var stream = new MemoryStream();
239+
240+
// Act
241+
using (var writer = new PdfWriter(stream))
242+
{
243+
writer.AddPage(page =>
244+
{
245+
page.MediaBox = Sizes.A4.AsRectangle();
246+
page.AddHyperlink(new Uri("https://example.com/"), new Rectangle(100, 100, 200, 130, Unit.Points));
247+
});
248+
}
249+
250+
// Assert
251+
stream.Position = 0;
252+
var pdfContent = System.Text.Encoding.ASCII.GetString(stream.ToArray());
253+
254+
Assert.Contains("/Annots", pdfContent); // page references the annotation
255+
Assert.Contains("/Subtype/Link", pdfContent); // it is a link annotation
256+
Assert.Contains("/S/URI", pdfContent); // with a URI action
257+
Assert.Contains("/Border[0 0 0]", pdfContent); // no visible border
258+
Assert.Contains("/F 4", pdfContent); // print flag
259+
// The uri itself is written as a hex string, so assert on the key rather than the raw url.
260+
Assert.Contains("/URI<", pdfContent);
261+
}
262+
263+
[Fact]
264+
public void Test_PdfWriter_AddHyperlink_WithRelativeUri_Throws()
265+
{
266+
// Arrange
267+
using var stream = new MemoryStream();
268+
269+
// Act & Assert
270+
// Note: the writer is intentionally not disposed here. A pageAction that throws leaves the
271+
// page's reserved objects unwritten, which would make writing the trailer (on Dispose) fail.
272+
var writer = new PdfWriter(stream);
273+
Assert.Throws<ArgumentException>(() =>
274+
{
275+
writer.AddPage(page =>
276+
{
277+
page.AddHyperlink(new Uri("/relative", UriKind.Relative), new Rectangle(0, 0, 10, 10, Unit.Points));
278+
});
279+
});
280+
}
233281
}

0 commit comments

Comments
 (0)