![.net下生成创建(较复杂表格,插图的)pdf文档 - 榕树下 - 少年 .net下生成创建(较复杂表格,插图的)pdf文档 - 榕树下 - 少年](http://img0.ph.126.net/ua75T_HCj0tXD-_B4fctMA==/1894889543316170160.jpg)
//创建PDF文档对象
string tempfile = filePath;
Document documents = new Document(PageSize.A4);
//实例化生成的文档
PdfWriter.GetInstance(documents, new FileStream(Server.MapPath(tempfile), FileMode.Create));
documents.Open();//打开文档
//要支持中文,必须添加引用对应的中文字体
BaseFont bfSun = BaseFont.CreateFont(@"c:\windows\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(bfSun, 16);
//添加表格
//程序逻辑,程序的单元格是自动按顺序添加,从第一行和第一列开始,然后是第二列,第一行满后转第二行第一列……
iTextSharp.text.Table table = new iTextSharp.text.Table(6);//创建6行三例表格
//table.BorderWidth = 0;//边框宽度
//table.BorderColor = new Color(51,178, 214);//边框颜色
table.Cellpadding = 5;//内间距
table.Cellspacing = 5;//间距
Cell cell = new Cell();//创建一个单元格
cell.Header = true;//显示表头
cell.Colspan = 6;//合并单元格
cell.AddElement(new Paragraph("星期一课程表", font));
cell.HorizontalAlignment = Element.ALIGN_CENTER;//设置居中
table.AddCell(cell);//添加表头单元格到表格
cell = new Cell();//创建一个单元格
cell.Rowspan = 2;//合并当前格和第三行的第一列单元格
//cell.BorderColor = new Color(255, 0, 0);//边框颜色
//cell.AddElement(new Paragraph("星期/科目/节次", font));
string imagePath = Server.MapPath("/2.jpg");//添加一张图片,主要是无法绘制星期/科目/节次之间的斜线
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(new Uri(imagePath));
cell.Add(jpg);
//cell.AddElement(new ImgRaw(iTextSharp.text.Image.GetInstance(Server.MapPath("/2.jpg"))));
table.AddCell(cell);//添加单元格到表格
//添加显示上午的单元格,合并三列
cell = new Cell();
cell.Colspan = 3;//合并三列,为上午的三节课
cell.AddElement(new Paragraph("上午", font));
table.AddCell(cell);//添加到表格
//同样方法添加显示下午的单元格,合并两列
cell = new Cell();
cell.Colspan = 2;
cell.AddElement(new Paragraph("下午",font));
table.AddCell(cell);
//第三行添加节次
cell = new Cell();
table.AddCell(new Paragraph("第一节", font));
table.AddCell(new Paragraph("第二节", font));
table.AddCell(new Paragraph("第三节", font));
table.AddCell(new Paragraph("第四节", font));
table.AddCell(new Paragraph("第五节", font));
//从第四行开始写课程,但第一列必须写星期
table.AddCell(new Paragraph("星期一", font));
table.AddCell(new Paragraph(TextBox1.Text, font));
table.AddCell(new Paragraph(TextBox2.Text, font));
table.AddCell(new Paragraph(TextBox3.Text, font));
table.AddCell(new Paragraph(TextBox4.Text, font));
table.AddCell(new Paragraph(TextBox5.Text, font));
documents.Add(table); //添加内容
documents.Close(); //关闭文档对象
Response.Redirect(tempfile);