pdf,iTextSharp,寫入表格數據

public class ApiPdf
    {
        private DataTable dt = null;

        public void GetData() {
            dt = new DataTable();
            dt.Columns.Add("id",typeof(string));
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("addr", typeof(string));
            var dr = dt.NewRow();
            dr["id"] = "001"; dr["name"] = "馬雲"; dr["addr"] = "浙江"; 
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["id"] = "002"; dr["name"] = "李彥宏"; dr["addr"] = "北京"; 
            dt.Rows.Add(dr); 
            dr = dt.NewRow();
            dr["id"] = "003"; dr["name"] = "馬化騰"; dr["addr"] = "深圳";  
            dt.Rows.Add(dr);
        }

        public void Create() {
            GetData(); 
            BaseFont basefont = BaseFont.CreateFont(@"c:\windows\fonts\simkai.ttf", 
                BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);


            Font f = new Font(basefont);

            FileStream pdf = new FileStream("D:\\desktop\\yfsoftDesktop\\123.pdf", FileMode.OpenOrCreate);
            Document doc = new Document(PageSize.A4);
            PdfWriter.GetInstance(doc, pdf); 
            doc.Open(); 
            PdfPTable table = new PdfPTable(3); 
            PdfPCell cell = new PdfPCell(new Phrase("中國企業家",f)); 
            cell.Colspan = 3; 
            cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right 
            table.AddCell(cell);
            table.AddCell(new Paragraph("編號",f));
            table.AddCell(new Paragraph("名稱", f));
            table.AddCell(new Paragraph("地址", f));
            foreach (DataRow r in dt.Rows)
            {
                foreach (DataColumn c in dt.Columns)
                {
                    string v = r[c.ColumnName] + "";
                    Paragraph pra = new Paragraph(v, f);
                    table.AddCell(pra);
                }
            } 
            doc.Add(table);
            doc.Close();

        }
    }

 

ApiPdf api = new ApiPdf();
            api.Create();
            System.Console.WriteLine("end");

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章