`
javajack
  • 浏览: 21803 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Itext应用封装(二)_生成表格

阅读更多

去年写了对itext封装,主要是向模板写数据,而在我们的项目中不是所有的表格都是用模板的,有些表格是动态的复杂的,有些是嵌套的,需要动态去生成表格及文档。

在这一部分中对生成表格进行了封装。

 

 

如:

根据行列生成表格:

	/**************************************************************************?/
	/**
	 * 根据行列数生成指定行列的空表格
	 * @param rows 行数
	 * @param cols 列数
	 * @return
	 */
	public PdfPTable createTable(int rows, int cols) {
		PdfPTable table = new PdfPTable(cols);
		
		for (int i = 0; i < rows * cols; i++) {
			PdfPCell cell;
			cell = new PdfPCell();

			cell.setFixedHeight(rowheight);
			table.addCell(cell);
		}
		table.setSpacingAfter(margin);
		table.setSpacingBefore(margin);
		return table;
	}

 

 

如根据行列生成表格:根据定制表格对象生成表格

 

	/**
	 * 根据指定单元格内容,生成表格,
	 * @param rows
	 * @param cols
	 * @param element 定制的表格对象
	 * @param db 数据对象,表格中存储的数据对象
	 * @return
	 */
	public PdfPTable createFreeTable(int rows, int cols, ElementTable et,DataBean db) {
		float[] colwidths = this.tp.getColwidths();
		float[] rowheights = this.tp.getRowheights();
		PdfPTable table = new PdfPTable(colwidths);
		
		table.setWidthPercentage(100f);
		Map<String, CellProperties> element = this
				.readElementTalbe(et, this.tp);
		int pan = 0;
		ArrayList<String> hascell = new ArrayList<String>();
		float tmprowheight = rowheight;

		for (int i = 0; i < rows; i++) {
			if (rowheights != null && i <= rowheights.length) {
				tmprowheight = rowheights[i];
			}
			for (int j = 0; j < cols; j++) {
				String key = i + "*" + j;
				if (hascell.contains(key))
					continue;
				PdfPCell cell;

				if (element.containsKey(key)) {
					CellProperties e = element.get(key);
					cell = this.getPdfPCell(e,db);
					//cell.setNoWrap(false);
					int type = e.getType();
					pan = e.getNum();
					// this.handlePdfPcell(cell, e);
					if (type == PConstant.rowspan) {
						cell.setRowspan(pan);
						for (int k = 1; k < pan; k++) {
							int tmprow;
							int tmpcol;
							tmprow = i + k;
							tmpcol = j;
							hascell.add(tmprow + "*" + tmpcol);
						}
					} else if (type == PConstant.colspan) {
						cell.setColspan(pan);
						for (int k = 1; k < pan; k++) {
							int tmprow;
							int tmpcol;
							tmprow = i;
							tmpcol = j + k;
							hascell.add(tmprow + "*" + tmpcol);
						}
					}
				} else
					cell = new PdfPCell();

				// 最小高度
				cell.setMinimumHeight(rowheight);
				cell.setFixedHeight(tmprowheight);

				table.addCell(cell);
			}
		}
		return table;
	}

 

其它的不在一一添加,附上所有代码及测试方法。

附件于2011年7月份完成,需要iText-2.1.7.jar及iTextAsian.jar的支撑。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics