2017-02-14 60 views
0
PdfContentByte canvas = writer.getDirectContent(); 
Rectangle rect = new Rectangle(0, 805, 594, 820); 
rect.setBorder(Rectangle.BOX); 
rect.setBorderWidth(1); 
rect.setBackgroundColor(BaseColor.GRAY); 
rect.setBorderColor(BaseColor.GREEN); 

ColumnText ct = new ColumnText(canvas); 
ct.setSimpleColumn(rect); 
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD); 

ct.addElement(new Paragraph("Your Text Goes here!! ",catFont)); 
ct.go(); 
canvas.rectangle(rect); 

document.newPage(); 
document.close(); 

這是我的代碼,這裏我試圖在矩形中添加文本。它沒有工作!該矩形被創建,但文本不顯示在PDF頁面的任何地方。使用itext5將文本添加到PDF中的矩形

回答

1

您的代碼有幾個問題導致文本無法顯示。

首先,在添加文本之後,將矩形添加到畫布。灰色背景將覆蓋繪製的任何文本,並隱藏它。其次,字體大小對於列邊界來說太大,所以不顯示文本。 您可以使您的矩形更大,文字將顯示或減少字體的大小。

例如,下面應該工作,因爲我已經增加了矩形高度和ColumnText.go()之前移動的canvas.rectangle()調用:

Rectangle rect = new Rectangle(0, 780, 494, 820); 
rect.setBorder(Rectangle.BOX); 
rect.setBorderWidth(1); 
rect.setBackgroundColor(BaseColor.GRAY); 
rect.setBorderColor(BaseColor.GREEN); 
canvas.rectangle(rect); 

ColumnText ct = new ColumnText(canvas); 
ct.setSimpleColumn(rect); 
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD); 
ct.addElement(new Paragraph("Your Text Goes here!! ", catFont)); 
ct.go(); 
+1

感謝@Palmr它的工作,我減少文字的大小從18到10,它的工作! –