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代码生成结果如下图所示: