在PDF文档中添加超链接

时间:2013-10-21 10:37:15

标签: pdf hyperlink itextsharp

我目前正在扩展我们的自定义PDF编写器,以便能够编写指向网站的链接。但是,我遇到了一个问题,因为我无法在任何地方找到如何将链接放入PDF中。

这就是打印文本的内容:

BT
70 50 TD
/F1 12 Tf
(visit my website!) Tj
ET

我现在需要的是将其包装成一个超链接,以便用户在点击“访问我的网站!”时被重定向到我的网站。

知道怎么做吗?我不能使用工具 - 我需要知道如何将正确的PDF命令写入文件,因为很多文档是使用C#动态生成的。目前我正在使用iTextSharp - 但我找不到编写超链接的任何功能,所以我决定添加此功能。

2 个答案:

答案 0 :(得分:5)

以下是规范方面的内容:链接是通过在页面上放置链接注释来创建的。链接注释由Rect键或一组四边形表示。我们假设你正在使用矩形。为了放置链接,您至少需要一个这样的字典:

<< /Type /Annot /Subtype /Link /Rect [ x1 y1 x2 y2 ] >>

(x1,y1)和(x2,y2)描述了链接活动区域所在矩形的角落。

要使用它,这应该是PDF中的间接对象,并从页面的Annots数组中引用。

如果你可以创建它,你将在页面上找到一个无处可寻的链接。

要使链接转到某个地方,您需要链接中的/ Dest或/ A条目(但不是两者)。 / Dest是页面级导航的旧工件 - 您不会使用它。而是使用/ A条目作为动作字典。因此,如果您想要导航到网址http://www.google.com,您可以使注释看起来像这样:

<< /Type /Annot /Subtype /Link /Rect [ x1 y1 x2 y2 ]
   /A << /Type /Action /S /URI /URI (http://www.google.com) >>
>>

我无法帮助您具体了解如何在iTextSharp中执行此操作。我并不特别喜欢他们使用的模型或抽象。我为Atalasoft编写了一个PDF工具包,我将向您展示如何在我自己的工具箱中执行此操作。再一次,我没有努力隐瞒这是一个商业产品,这就是我的生活。我只是想让你看到还有其他选择。

// make a document, add a font, get its metrics
PdfGeneratedDocument doc = new PdfGeneratedDocument();
string fontResource = doc.Resources.Fonts.AddFromFontName("Times New Roman");
PdfFontMetrics mets = doc.Resources.Fonts.Get(fontResource).Metrics;

// make a page, place a line of text
PdfGeneratedPage page = doc.Pages.AddPage(PdfDefaultPages.Letter);
PdfTextLine line = new PdfTextLine(fontResource, 12.0, "Visit my web site.",
                        new PdfPoint(72, 400));
page.DrawingList.Add(line);

// get the bounds of the text we place, make an annotation
PdfBounds bounds = mets.GetTextBounds(12.0, "Visit my web site.");
bounds = new PdfBounds(72, 400, bounds.Width, bounds.Height);
LinkAnnotation annot = new LinkAnnotation(bounds, new PdfURIAction(new URI("my url")));
page.Annotations.Add(annot);

// save the content
doc.Save("finaldoc.pdf");

唯一“棘手”的是,页面上的内容和链接注释之间存在分离 - 但这是因为这是Acrobat模型链接的方式。如果要修改现有文档,则应从现有文件/流构造PdfGeneratedDocument,添加注释然后保存。

答案 1 :(得分:1)

  

目前我正在使用iTextSharp - 但我找不到编写超链接的任何功能。

查看iText in Action, 2nd Edition Webified iTextSharp Examples MovieLinks2.csLinkActions.cs

// create an external link
Chunk imdb = new Chunk("Internet Movie Database", FilmFonts.ITALIC);
imdb.SetAnchor(new Uri("http://www.imdb.com/"));
p = new Paragraph("Click on a country, and you'll get a list of movies, containing links to the ");
p.Add(imdb);
p.Add(".");
document.Add(p);

因此,使用iTextSharp添加链接真的很简单。

如果您仍想手动执行此操作,请查看PDF specification。第12.5.6.5节解释了链接注释,第12.6.4.7节显示了要在该链接注释中使用的 URI操作