天天看点

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");