2016-02-09 61 views
2

我已經實現了一個通用的方法來創建PDFPCell,並且它適用於文本字段。 在這裏我正在尋找一些代碼,可以幫助我添加網址(熱鏈接)。 在此先感謝。如何使用iText將URL添加到PDF文檔?

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; 
} 
+3

我你的票你想整個小區被點擊,或在細胞中只是內容? –

回答

3

請看看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

+1

嗨布魯諾,我們如何提供在新標籤打開? –

+1

這不包括在ISO-32000-1中,因此沒有辦法做到這一點。無論在PDF規範中未定義什麼,都無法實現。 –

+0

感謝您的反饋,怎麼樣在PDF中使用JavaScript? –

相關問題