很久沒有發文章了,是因爲現在做技術比較少了,開始轉型做管理,不過還是有一些小問題需要我來處理,在項目中原來都是主要導出execl文件,而現在要求導出pdf文件。
後來找了找資料做了個例子和大家分享。
首先:c#導出pdf需要用到一個類就是itextsharp.dll,在網上可以找到。
第二部:寫一個導出類
有三個參數:Data 爲包含要導出的數據的數據表;FontPath爲字體文件的路徑(需要一個字體就pdf 的文件內容進行定義顯示);FontSize爲字體大小。
方法用例:OutPdf(CreateTable(), Server.MapPath("Bin/msyh.ttf"), 10);
/* Data 爲包含要導出的數據的數據表(DataTable)*/
/* FontPath爲字體文件的路徑*/
/* FontSize爲字體大小*/
public static void OutPdf(DataTable Data, string FontPath, float FontSize)
{
// step 1
// need to write to memory first due to IE wanting to know the length of the pdf beforehand
MemoryStream m = new MemoryStream();
Document document = new Document();
try
{
// step 2: we set the ContentType and create an instance of the Writer
HttpContext.Current.Response.ContentType = "application/pdf";
PdfWriter.GetInstance(document, m);
// step 3
document.Open();
//定義字體
BaseFont baseFont =
BaseFont.CreateFont(
FontPath,
BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, FontSize);
//添加內容
PdfPTable table = new PdfPTable(Data.Columns.Count);
for (int i = 0; i < Data.Rows.Count; i++)
{
for (int j = 0; j < Data.Columns.Count; j++)
{
table.AddCell(new Phrase(Data.Rows[i][j].ToString(), font));
}
}
document.Add(table);
}
catch (DocumentException ex)
{
HttpContext.Current.Response.Write(ex.Message);
}
document.Close();
string filename = "1122";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;FileName=" + filename + ".pdf");
HttpContext.Current.Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
HttpContext.Current.Response.OutputStream.Flush();
HttpContext.Current.Response.OutputStream.Close();
}
我做了一個小例子在我的資源空間裏,歡迎大家下載:http://download.csdn.net/detail/lzy_1515/5486629