itextsharp 用于生成PDF文件,主要五个步骤,
1.创建一个iTextsharp.text.Document 对象的实例
2.为该Document创建一个Writer实例
3.打开当前Document
4.为当前Document添加内容
5.关闭Document
--示例代码
Document doc = new Document(PageSize.A4.Rotate()); FileStream fs = new FileStream(context.Server.MapPath("~/TempFile/" + filename), FileMode.Create); PdfWriter.GetInstance(doc, fs); doc.Open();
/*设置字体字形*/ BaseFont bfChinese = BaseFont.CreateFont(@"c:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font fontChinese = new Font(bfChinese, 10, Font.NORMAL, new iTextSharp.text.Color(0, 0, 0)); /*doc添加各种元素*/ ... doc.Close()
块,短句和段落
1.Chunk: 能被添加到文档的最小单位,Chunk c1 = new Chunk("销售订单",font)
2.Phrase :比Chunk大一点,可添加多个Chunk
3.Paragraph:
public void AddParagraph(Document document, string para, int align, Font font) { Paragraph p = new Paragraph(para, font);
p.Alignment = align; document.Add(p); }
列表
iTextSharp.text.List li = new iTextSharp.text.List(List.ORDERED); li.IndentationLeft = 210f; foreach (DataRow row in ds.Tables[0].Rows) { li.Add(new ListItem(new Phrase(row["file_name"].ToString(), fontChinese))); }
表格
//添加datatable public void AddTable(Document document, float[] f, DataTable Dt, Font font, float totalwidth, bool islock) { PdfPTable table = new PdfPTable(f); table.TotalWidth = totalwidth; table.LockedWidth = islock; table.SpacingBefore = 10f; for (int i = 0; i < Dt.Rows.Count; i++) { for (int j = 0; j < Dt.Columns.Count; j++) { table.AddCell(new Phrase(Dt.Rows[i][j].ToString(), font)); } } document.Add(table); }
//增加表格元素 public PdfPCell SetCell(string str, Font font, float padding, int align,int border,int colspan,int vertical) { PdfPCell cell = new PdfPCell(new Phrase(str, font)); cell.PaddingBottom = padding + 1f; cell.PaddingLeft = padding; cell.PaddingRight = padding; cell.PaddingTop = padding; cell.HorizontalAlignment = align;//查看Element 1水平居中 //switch (vertical) { // case 0: cell.VerticalAlignment = Element.ALIGN_JUSTIFIED; break; // case 1: cell.VerticalAlignment = Element.ALIGN_MIDDLE; break; // default: break; //} //cell.VerticalAlignment = Element.ALIGN_JUSTIFIED; //cell.VerticalAlignment = Element.ALIGN_CENTER; cell.VerticalAlignment = Element.ALIGN_MIDDLE; ; cell.Border = border; cell.Colspan = colspan; return cell; }