2013年8月14日 星期三

[C#] 網頁Html轉PDF檔(一行程式碼解決)

網頁轉PDF檔做法很多(Convert HTML to PDF in .NET)
這邊紀錄一下老外最多人加分的那篇做法,使用wkhtmtopdf(採GPL授權)可以省很多程式碼

首先到官網http://code.google.com/p/wkhtmltopdf/downloads/list
找installer.exe下載,這邊Demo我是下載wkhtmltopdf-0.9.9-installer.exe
下載完後執行安裝它



另外GridView匯出PDF的話,請參考:
ASP.NET 輕鬆轉 GridView 資料轉檔到 PDF - 使用 iTextSharp

請注意使用iTextSharp預設不支援中文字和背景色
中文字的解決方案:GridView透過iTextSharp輸出PDF中文問題

原始介紹文章出自於此


----------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
/*要引用以下命名空間*/
using System.Diagnostics;
using System.IO;

public partial class _Default : System.Web.UI.Page
{

    //Button的Click事件(把Url的網頁內容轉成PDF)
    protected void btn_execute_Click(object sender, EventArgs e)
    {

        //因為Web 是多執行緒環境,避免甲產生的文件被乙下載去,所以檔名都用唯一
        string fileNameWithOutExtention = Guid.NewGuid().ToString();

        //執行wkhtmltopdf.exe
        Process p = System.Diagnostics.Process.Start(@"D:\wkhtmltopdf\wkhtmltopdf.exe", @"http://msdn.microsoft.com/zh-cn D:\" + fileNameWithOutExtention + ".pdf");

        //若不加這一行,程式就會馬上執行下一句而抓不到檔案發生例外:System.IO.FileNotFoundException: 找不到檔案 ''。
        p.WaitForExit();


       //把檔案讀進串流
       FileStream fs = new FileStream(@"D:\" + fileNameWithOutExtention + ".pdf", FileMode.Open);
       byte[] file = new byte[fs.Length];
       fs.Read(file, 0, file.Length);
       fs.Close();

       //Response給用戶端下載
       Response.Clear();
       Response.AddHeader("content-disposition", "attachment; filename="+fileNameWithOutExtention+".pdf");//強制下載
       Response.ContentType = "application/octet-stream";
       Response.BinaryWrite(file);

      
    }
}

沒有留言:

張貼留言