iText7合并表格(java)
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.UnitValue;
import com.itextpdf.layout.property.VerticalAlignment;
import java.io.File;
public class SimpleRowColspan {
public static final String DEST = "C:/Users/test/Desktop/test.pdf";
public static void main(String[] args) throws Exception {
File file = new File(DEST);
new SimpleRowColspan().manipulatePdf(DEST);
}
protected void manipulatePdf(String dest) throws Exception {
PdfFont chineseFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Table tableB = new Table(UnitValue.createPercentArray(new float[]{30, 30, 40}));
Cell ce = new Cell();
Cell cell = new Cell(5, 1).add(new Paragraph("名称"));
cell = formatCell(cell, 20);
tableB.addCell(cell);
cell = new Cell( 2, 1).add(new Paragraph("类别"));
cell = formatCell(cell, 20);
tableB.addCell(cell);
//对应起前面的2
cell = new Cell(1, 1).add(new Paragraph("等级"));
cell = formatCell(cell, 20);
tableB.addCell(cell);
cell = new Cell(1, 1).add(new Paragraph("层数1"));
cell = formatCell(cell, 20);
tableB.addCell(cell);
// --------------------------------------------------------
cell = new Cell(3, 1).add(new Paragraph("层数2"));
cell = formatCell(cell, 20);
tableB.addCell(cell);
//对应前面的3
cell = new Cell(1, 1).add(new Paragraph("层数3"));
cell = formatCell(cell, 20);
tableB.addCell(cell);
cell = new Cell(1, 1).add(new Paragraph("层数4"));
cell = formatCell(cell, 20);
tableB.addCell(cell);
cell = new Cell(1, 1).add(new Paragraph("层数4"));
cell = formatCell(cell, 20);
tableB.addCell(cell);
tableB = initTable(tableB, 80, HorizontalAlignment.CENTER, 0, chineseFont);
doc.add(tableB);
doc.close();
}
public Table initTable(Table table, int width, HorizontalAlignment horizontalAlignment, int marginTop, PdfFont chineseFont, Cell... cells) {
for (Cell c : cells) {
table.addCell(c);
}
table.setWidth(UnitValue.createPercentValue(width)); // 设置表格宽度
table.setHorizontalAlignment(horizontalAlignment); // 设置水平对齐方式
table.setMarginTop(marginTop); // 设置上边距
table.setFont(chineseFont);
table.setTextAlignment(TextAlignment.CENTER);
return table;
}
public Cell formatCell(Cell cell, float height) {
cell.setTextAlignment(TextAlignment.CENTER);
cell.setVerticalAlignment(VerticalAlignment.MIDDLE);
cell.setHeight(height);
return cell;
}
}
结果示例
需要合并列修改new Cell(rowspan,colspan) 中的参数即可。