Java IText:锚点(链接)
时间:2020-01-09 10:36:08 来源:igfitidea点击:
IText中的com.itextpdf.text.Anchor类表示到外部网站或者文档内部的链接。就像网页中的链接一样,可以单击锚点(链接)。
这是一个简单的代码示例:
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class AnchorExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Anchor.pdf"));
document.open();
Paragraph paragraph = new Paragraph();
paragraph.add(new Phrase("You can find the IText tutorial at "));
Anchor anchor = new Anchor(
"http://theitroad.local/java-itext/index.html");
anchor.setReference(
"http://theitroad.local/java-itext/index.html");
paragraph.add(anchor);
document.add(paragraph);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
注意鼠标指针的形状是手。这意味着我们现在可以单击文本。另请注意,默认情况下,锚没有任何特殊样式。我们将必须自己添加。
内部连结
我们也可以在文档中创建内部链接,就像HTML页面中的内部链接一样。就像在HTML中一样,我们需要链接和目标锚(带有名称的锚)。这是一个代码示例:
import com.itextpdf.text.Anchor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
*/
public class Anchor2Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Anchor2.pdf"));
document.open();
Anchor anchor =
new Anchor("Jump down to next paragraph");
anchor.setReference("#linkTarget");
Paragraph paragraph = new Paragraph();
paragraph.add(anchor);
document.add(paragraph);
Anchor anchorTarget =
new Anchor("This is the target of the link above");
anchor.setName("linkTarget");
Paragraph targetParagraph = new Paragraph();
targetParagraph.setSpacingBefore(50);
targetParagraph.add(anchorTarget);
document.add(targetParagraph);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
这是结果文件。请注意,鼠标指针是如何再次变成手形的。由于链接的目标位于同一页面的正下方,因此单击链接时Adobe Reader可能不会做出反应。但是,如果目标段落位于其他页面上,则Adobe Reader会跳至该页面。

