摘要:[ASP.NET] 利用itextsharp元件把GridView變成PDF
今天有空剛好把USER需求記錄起來
這次要把GridView轉成PDF檔
利用itextsharp元件來作http://sourceforge.net/projects/itextsharp/files/itextsharp/iTextSharp-5.0.4/itextsharp-5.0.4-dll.zip/download
不多說直接看CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>GridView匯出PDF</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="匯出至PDF" onclick="Button1_Click" />
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
後端程式碼:
protected void Button1_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("content-disposition", "attachment;filename=Y2J.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
System.IO.StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
StringReader reader = new StringReader(stringWrite.ToString());
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, Response.OutputStream);
//設定中文
BaseFont BaseF = BaseFont.CreateFont("C:\\Windows\\Fonts\\kaiu.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font fontCh = new Font(BaseF, 14);
doc.Open();
int gvRowsCount = GridView1.Rows[0].Cells.Count;
PdfPTable ptb = new PdfPTable(gvRowsCount);
//表格標題
for (int h = 0; h < gvRowsCount; h++)
{
ptb.AddCell(new Phrase(GridView1.HeaderRow.Cells[h].Text, fontCh));
}
ptb.HeaderRows = 1;
//表格內文
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int j = 0; j < gvRowsCount; j++)
{
ptb.AddCell(new Phrase(GridView1.Rows[i].Cells[j].Text, fontCh));
}
}
//寫入並關閉
doc.Add(ptb);
doc.Close();
}
Y2J's Life:http://kimenyeh.blogspot.tw/