首先當然是將iTextSharp載回來加入參考,然後引用:
<%@ Import Namespace=" iTextSharp.text" %>程式:
<%@ Import Namespace=" iTextSharp.text.pdf" %>
<%@ Import Namespace="iTextSharp.text.html.simpleparser" %>
//--輸出PDF後來中文問題~將GridView轉成PDFPTable來解決。
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("content-disposition", "attachment;filename=CusInvNo.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
System.IO.StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.DataBind();
StringReader reader = new StringReader(stringWrite.ToString());
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, Response.OutputStream);
/*若要將檔案放在Server上
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(HttpContext.Current.Server.MapPath("TEST.pdf"), FileMode.Create));
*/
//0.處理中文~設定中文字型
string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.System) +@"\..\Fonts\kaiu.ttf";
BaseFont BaseF = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font fontCh = new Font(BaseF, 12);
doc.Open();
//1.將GridView轉為PdfPTable
PdfPTable ptb = new PdfPTable(GridView1.Columns.Count);
//表格標題
for (int h = 0; h < GridView1.Columns.Count; 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 < GridView1.Columns.Count; j++)
{
ptb.AddCell(new Phrase(GridView1.Rows[i].Cells[j].Text, fontCh));
}
}
//2.輸出
doc.Add(ptb);
doc.Close();
沒有留言:
張貼留言