这个简短的教程指导如何使用 C# 在 PDF 中添加超链接。它包含建立环境所需的必要资源、以步骤形式详细描述的过程,以及使用 C#** 在 PDF 中插入链接的可运行示例代码。您还将了解根据要求自定义超链接及其文本的过程。
使用 C# 创建 PDF 链接的步骤
- 建立使用Aspose.PDF for .NET添加超链接的环境
- 使用 Document 类对象打开目标 PDF 并获取对所需页面的引用
- 创建一个 LinkAnnotation 对象并在将其添加到页面之前设置其属性(包括 URI)
- 创建一个 FreeTextAnnotation 对象并设置要在链接上显示的文本
- 将这两个注释添加到页面
- 将生成的 PDF 文件保存在包含超链接的磁盘上
上述步骤详细说明了如何使用 C# 在 PDF 中添加链接的过程,首先加载源 PDF 文件,然后访问要添加超链接的第一页。在接下来的步骤中,将在具有不可见边框的矩形内创建链接注释,并在具有相同大小和相似不可见边框的矩形内的相同位置创建文本注释,从而重叠链接区域和文本区域以创建超链接。最后,这两个注释都被添加到选定的 PDF 页面,生成的 PDF 文件被保存在磁盘上。
使用 C# 将链接添加到 PDF 的代码
using Aspose.Pdf; | |
using Aspose.Pdf.Annotations; | |
namespace AsposeProjects | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to add hyperlink to a PDF using C# | |
{ | |
// Initialize license | |
License lic = new License(); | |
lic.SetLicense("Aspose.Total.lic"); | |
// Open the document | |
Document document = new Document("AddHyperlink.pdf"); | |
// Get a reference to the first page | |
Page page = document.Pages[1]; | |
// Create a Link annotation object by setting its rectangular area, border and URI | |
LinkAnnotation link = new LinkAnnotation(page, new Aspose.Pdf.Rectangle(100, 100, 300, 300)); | |
Border border = new Border(link); | |
border.Width = 0; | |
link.Border = border; | |
link.Action = new GoToURIAction("www.aspose.com"); | |
// Add the link annotation to the target page | |
page.Annotations.Add(link); | |
// Create Free Text annotation by setting its rectangular area, appearance, color, contents, and border | |
FreeTextAnnotation textAnnotation = new FreeTextAnnotation(document.Pages[1], | |
new Aspose.Pdf.Rectangle(100, 100, 300, 300), | |
new DefaultAppearance( | |
Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman"), | |
10, System.Drawing.Color.Blue)); | |
textAnnotation.Contents = "Link to Aspose website"; | |
// Set same border as used for link annotation | |
textAnnotation.Border = border; | |
// Add the FreeText annotation also to the annotations collection of the target page of the document | |
page.Annotations.Add(textAnnotation); | |
// Save the updated document | |
document.Save("Output.pdf"); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
上述示例代码演示了如何使用 C# 创建指向 PDF 的链接的过程,其中 LinkAnnotation 对象用于通过提供 URI、设置其边框和 0 宽度来创建实际链接,并将操作设置为打开设置了 URL 的目标页面。同样,在创建用于显示超链接文本的 FreeTextAnnotation 对象时,会定义矩形,并设置外观以及字体和颜色设置。请注意,还可以为这些注释设置许多其他属性。
在本主题中,我们学习了使用 C#* 在 PDF 中嵌入链接的过程。如果您想了解在 PDF 文件中添加页眉和页脚的过程,请参阅 如何使用 C# 在 PDF 中添加页眉和页脚 上的文章。