.NET动态生成PDF文件(利用iTextSharp)

1.前台页面上:


       
     
       
 

2。后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
static DataTable datatable = new DataTable("testpdf");
    protected void Page_Load(object sender, EventArgs e)
   {
     
        if (!Page.IsPostBack)
        {
         DataRow dr;
        //建立Column例,可以指明例的类型,这里用的是默认的string
        datatable.Columns.Add(new DataColumn("呵呵"));
        datatable.Columns.Add(new DataColumn("哈哈"));
        for (int i = 1; i < 5; i++)
       {
            dr = datatable.NewRow();
            dr[0] = System.Convert.ToString(i);
            dr[1] = "红叶锁清秋" + System.Convert.ToString(i);
            datatable.Rows.Add(dr);
        }
        }
       
       
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
         try
       {
            Document document = new Document();
            PdfWriter.GetInstance(document, new FileStream(Server.MapPath("Chap0107.pdf"), FileMode.Create));
                        document.Open();
            BaseFont bfChinese = BaseFont.CreateFont("C://WINDOWS//Fonts//simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font fontChinese = new Font(bfChinese, 12, Font.NORMAL,new Color(0, 0, 0));

                        document.Add(new Paragraph(this.TextBox1.Text.ToString(), fontChinese));
                       

            //iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(Server.MapPath("pic015.jpg"));
            //document.Add(jpeg);
            PdfPTable table = new PdfPTable(datatable.Columns.Count);
         
            for (int i = 0; i < datatable.Rows.Count; i++)
         {
                for (int j = 0; j < datatable.Columns.Count; j++)
              {
                    table.AddCell(new Phrase(datatable.Rows[i][j].ToString(), fontChinese));
                }
            }
            document.Add(table);

            document.Close();
        }
        catch (DocumentException de)
     {
            Response.Write(de.ToString());
        }
    }
}

你可能感兴趣的:(.NET编程类,.NET第三方控件,底层类的编写,自己写的控件)