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

Len*_*oju 3 java url itext

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

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;
}
Run Code Online (Sandbox Code Playgroud)

Bru*_*gie 7

请看一下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);
Run Code Online (Sandbox Code Playgroud)

在此示例中,我们创建一个单元格,其内容为“ iText的创建者被提名为欧洲企业大奖!”。单击文本“欧洲商业奖!”时,您将转到博客文章

方法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);
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

无论您在单元格中的何处单击(不仅单击文本时),现在都将您转发到另一篇博客文章

如果这个答案有帮助,您可能想让我和我的妻子参加欧洲商业大奖