如何使用iText将URL添加到PDF文档?

时间:2016-02-09 09:25:28

标签: java url itext

我已经实现了创建PDFPCell的通用方法,它适用于文本字段。 在这里,我正在寻找一些可以帮助我添加网址(热门链接)的代码。 提前谢谢。

public PdfPCell createCell(String text, Font font, BaseColor bColor, int rowSpan, int colSpan, int hAlign, int vAlign) {
    PdfPCell cell = new PdfPCell(new Phrase(text, font));
    cell.setBackgroundColor(bColor);
    cell.setRowspan(rowSpan);
    cell.setColspan(colSpan);
    cell.setHorizontalAlignment(hAlign);
    cell.setVerticalAlignment(hAlign);
    cell.setMinimumHeight(20);
    cell.setNoWrap(true);
    return cell;
}

1 个答案:

答案 0 :(得分:5)

请查看LinkInTableCell示例。它演示了在单元格中添加链接的两种不同方法。

方法#1:添加指向(部分)短语的链接。

Phrase phrase = new Phrase();
phrase.add("The founders of iText are nominated for a ");
Chunk chunk = new Chunk("European Business Award!");
chunk.setAnchor("http://itextpdf.com/blog/european-business-award-kick-ceremony");
phrase.add(chunk);
table.addCell(phrase);

在这个例子中,我们创建了一个内容为“iText的创始人被提名为欧洲商业奖!”的单元格。当您点击“欧洲商业奖!”文本时,您会转到a blog post

方法#2:将链接添加到完整单元格

在这种方法中,我们向细胞添加一个细胞事件:

PdfPCell cell = new PdfPCell(new Phrase("Help us win a European Business Award!"));
cell.setCellEvent(new LinkInCell(
    "http://itextpdf.com/blog/help-us-win-european-business-award"));
table.addCell(cell);

单元格事件的实现如下所示:

class LinkInCell implements PdfPCellEvent {
    protected String url;
    public LinkInCell(String url) {
        this.url = url;
    }
    public void cellLayout(PdfPCell cell, Rectangle position,
        PdfContentByte[] canvases) {
        PdfWriter writer = canvases[0].getPdfWriter();
        PdfAction action = new PdfAction(url);
        PdfAnnotation link = PdfAnnotation.createLink(
            writer, position, PdfAnnotation.HIGHLIGHT_INVERT, action);
        writer.addAnnotation(link);
    }
}

无论您在单元格中单击的位置(不仅在单击文本时),现在都会转发到another blog post

如果这个答案有帮助,你可能想给我的妻子和我投票给European Business Awards