[ASP.NET MVC]轉換URL為PDF

不使用wkhtmltopdf和itextsharp也能輕鬆完成轉換PDF

早期要將URL或 Html page轉換為PDF供使用者下載,我大部分都是透過wkhtmltopdf或itextsharp來完成,

但最近發現另一個套件Select.Pdf可以更簡單快速完成,重點是也有提供Community Edition版本供大家免費使用,

簡單示範在ASP.net MVC中,如何使用Select.Pdf將URL轉換PDF供使用者下載。

 

Controller

using SelectPdf;
public ActionResult ToPdf()
        {
            // instantiate a html to pdf converter object
            string pdfname = "Sample.pdf";
            HtmlToPdf converter = new HtmlToPdf();
            //var fullUrl = this.Url.Action("Posts", "Edit", new { id = 5 }, this.Request.Url.Scheme);
            //Request.RequestUri.PathAndQuery
            var fullurl = this.Url.Action("Index", "Home", null, this.Request.Url.Scheme);
            // create a new pdf document converting an url
            PdfDocument doc = converter.ConvertUrl(fullurl);
            MemoryStream stream = new MemoryStream();
            // save pdf document   
            doc.Save(stream);    
            //doc.Save(System.Web.HttpContext.Current.Response, false, pdfname);
            //close pdf document
            doc.Close();
            stream.Position = 0;
            return File(stream, "application/pdf", pdfname);
        }

View

  @Html.ActionLink("URL轉換PDF", "ToPdf")

Note:Select.Html.dep檔案記得和Select.HtmlToPdf.dll至於相同路徑(如bin)

執行Home/Index轉換

PDF檔案內容

參考

SelectPdf Html To Pdf Converter for .NET – Community Edition

https://visualstudiogallery.msdn.microsoft.com/fe0ef7ec-9546-45a4-bc82-725e4123a0a2

How to fix: Conversion failure. Could not find ‘Select.Html.dep’.