读书人

iText - 合拢单元格

发布时间: 2012-08-21 13:00:22 作者: rapoo

iText - 合并单元格

?

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

?

ADBC

?


可考虑在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 132             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 column38             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 255             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 }转载

读书人网 >编程

热点推荐