Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add URL to PDF document using iText?

Tags:

java

url

itext

I have implemented a generic method to create PDFPCell and it is fine for text fields. Here I am looking for some code which can help me to add url (hot links). Thanks in advance.

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;
}
like image 982
Leninkumar Koppoju Avatar asked Dec 25 '22 09:12

Leninkumar Koppoju


1 Answers

Please take a look at the LinkInTableCell example. It demonstrates two different approaches to add a link in a cell.

Approach #1: add the link to (part of) the phrase.

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);

In this example, we create a cell with the content "The founders of iText are nominated for a European Business Award!". When you click on the text "European Business Award!", you go to a blog post.

Approach #2: add the link to the complete cell

In this approach we add a cell event to the cell:

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);

The implementation of the cell event looks like this:

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);
    }
}

Wherever you click in the cell (not only when you click on text), you are now forwarded to another blog post.

If this answer was helpful, you might want to give my wife and I your vote for the European Business Awards

like image 176
Bruno Lowagie Avatar answered Dec 28 '22 07:12

Bruno Lowagie