java合并单元格两行,合并表格的单元格,iText中的setColspan或setRowspan方法

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

A

D

B

C

itext-5.4.5.zip下载地址:itext-5.4.5.zip

如果是输出中文pdf,需要用到itext-asian.jar这个jar包,这个jar包在extrajars-2.3.zip中,下载地址:extrajars-2.3.zip

更多Itext的信息,请点这里

完整代码如下:

import java.io.FileOutputStream;

import java.io.IOException;

import com.itextpdf.text.BaseColor;

import com.itextpdf.text.Chunk;

import com.itextpdf.text.Document;

import com.itextpdf.text.DocumentException;

import com.itextpdf.text.Element;

import com.itextpdf.text.Font;

import com.itextpdf.text.PageSize;

import com.itextpdf.text.Paragraph;

import com.itextpdf.text.Rectangle;

import com.itextpdf.text.pdf.BaseFont;

import com.itextpdf.text.pdf.PdfContentByte;

import com.itextpdf.text.pdf.PdfGState;

import com.itextpdf.text.pdf.PdfPCell;

import com.itextpdf.text.pdf.PdfPTable;

import com.itextpdf.text.pdf.PdfReader;

import com.itextpdf.text.pdf.PdfStamper;

import com.itextpdf.text.pdf.PdfWriter;

public class ItextHelloword {

public static void main(String[] args) throws Exception {

tableOutput2("f:/itext-demo222.pdf");

}

public static void tableOutput2(String pdfFilePath) throws Exception {

Document document = new Document(PageSize.A4);

PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath));

// 添加 中文信息

BaseFont bfCN = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H",

false);

// 设置字体大小

Font fontCN = new Font(bfCN, 12, Font.NORMAL, BaseColor.BLACK);

// 打开文档

document.open();

PdfPCell cell = null;

// 创建需要填入文档的元素

PdfPTable table = new PdfPTable(3);

table.setHorizontalAlignment(Element.ALIGN_CENTER);

table.setWidthPercentage(100);

cell = new PdfPCell(new Paragraph(

new Paragraph(" A ", new Font(fontCN))));

cell.setColspan(2);

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

table.addCell(cell);

cell = new PdfPCell(new Paragraph(

new Paragraph(" D ", new Font(fontCN))));

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

cell.setRowspan(2);

table.addCell(cell);

cell = new PdfPCell(new Paragraph(

new Paragraph("B ", new Font(fontCN))));

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

table.addCell(cell);

cell = new PdfPCell(new Paragraph(

new Paragraph("C ", new Font(fontCN))));

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

table.addCell(cell);

cell = new PdfPCell(new Paragraph(

new Paragraph(" ", new Font(fontCN))));

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

table.addCell(cell);

document.add(table);

// 6.关闭文档

document.close();

}

}

以上Itext代码生成结果如下图所示:

d5d03d413f53c06998159131ea3ab609.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值