iText - 合并单元格

 

iText中的PdfPTable和PdfPCell仅提供了合并列的功能(通过cell.setColspan(cellCount)实现),并未提供合并行的方法。如果需要生成下列表格,怎么实现呢?

 

A
D
B
C

 


可考虑在cell中添加一个表格来实现。对于上列表格,需先建立一个2列的表格。在表格的第一列中填充一个2行的表格即可。具体代码如下:

 

 
  
1 package itext; 2 3 import java.io.FileOutputStream; 4 5 import com.lowagie.text.Element; 6 import com.lowagie.text.PageSize; 7 import com.lowagie.text.Paragraph; 8 import com.lowagie.text.pdf.PdfPCell; 9 import com.lowagie.text.pdf.PdfPTable; 10 import com.lowagie.text.pdf.PdfWriter; 11 12 public class MergeCell { 13 14 public static void main(String[] args) { 15 String tmpPath = "c:\\test.pdf"; 16 PdfPCell cell; 17 PdfPCell iCell; 18 PdfPTable iTable; 19 float lineHeight1 = ( float)25.0; 20 float lineHeight2 = ( float)25.0; 21 try{ 22 Document pdfDoc = new Document(PageSize.A4.rotate(), 36, 36, 24, 36); 23 24 PdfWriter.getInstance(pdfDoc, new FileOutputStream(tmpPath)); 25 26 pdfDoc.open(); 27 28 PdfPTable headerTable = new PdfPTable(2); 29 headerTable.setWidthPercentage(40); 30 31 // create a table to fill cell 1 32 iTable = new PdfPTable(2); 33 iCell = new PdfPCell( new Paragraph("A")); 34 iCell.setHorizontalAlignment(Element.ALIGN_CENTER); 35 iCell.setVerticalAlignment(Element.ALIGN_MIDDLE); 36 iCell.setFixedHeight(lineHeight1); 37 // merge column 38 iCell.setColspan(2); 39 iTable.addCell(iCell); 40 iCell = new PdfPCell( new Paragraph("B")); 41 iCell.setHorizontalAlignment(Element.ALIGN_CENTER); 42 iCell.setVerticalAlignment(Element.ALIGN_MIDDLE); 43 iCell.setFixedHeight(lineHeight2); 44 iTable.addCell(iCell); 45 iCell = new PdfPCell( new Paragraph("C")); 46 iCell.setHorizontalAlignment(Element.ALIGN_CENTER); 47 iCell.setVerticalAlignment(Element.ALIGN_MIDDLE); 48 iCell.setFixedHeight(lineHeight2); 49 iTable.addCell(iCell); 50 cell = new PdfPCell(iTable); 51 cell.setPadding(0); 52 headerTable.addCell(cell); 53 54 // fill cell 2 55 cell = new PdfPCell( new Paragraph("D")); 56 cell.setHorizontalAlignment(Element.ALIGN_CENTER); 57 cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 58 cell.setPadding(0); 59 cell.setFixedHeight(lineHeight1+lineHeight2); 60 headerTable.addCell(cell); 61 62 pdfDoc.add(headerTable); 63 64 pdfDoc.close(); 65 66 } catch(Exception e) { 67 e.printStackTrace(); 68 } 69 } 70 }
转载
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值