既然用到了pdf
基本上就一定会用到表格
下面的例子就是一个使用itext进行表格的生成
基本上就一定会用到表格
下面的例子就是一个使用itext进行表格的生成
package test.pdf;
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
/**
* 创建表格
*
*/
public class Simple4 {
@SuppressWarnings("deprecation")
public static void main(String[] args) throws DocumentException, IOException {
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("E:/HelloWorld.pdf"));
doc.open();
//这里我们一一个2*5的表格为例
float[] widths = {120f, 220f};//设置表格的列宽
PdfPTable table = new PdfPTable(widths);//建立一个pdf表格
table.setSpacingBefore(130f);//设置表格上面空白宽度
table.setTotalWidth(342f);//设置表格的宽度
table.setLockedWidth(true);//设置表格的宽度固定
PdfPCell cell = new PdfPCell(new Paragraph("id"));//建立一个单元格
table.addCell(cell);//增加单元格
cell = new PdfPCell(new Paragraph("name"));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("1"));
cell.setBackgroundColor(new Color(212,208,200));//设置单元格的背景颜色
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Joy"));
cell.setFixedHeight(30);//设置单元格的高度
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置单元格垂直对齐方式
table.addCell(cell);
cell = new PdfPCell(new Paragraph("2"));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Join"));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("3"));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Tom"));
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Num = 3"));
cell.setColspan(2);//设置合并单元格
cell.setBorder(0);//设置单元格无边框
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);//设置单元格中的文字水平对齐方式
table.addCell(cell);
doc.add(table);
doc.close();
}
}