Để chuyển 1 trang Html thành file pdf, có khá nhiều thư viện miễn phí lẫn có phí như iTextSharp, WkHtmlToPdf, Prince, Pechkin(.NET Wrapper for WkHtmlToPdf static DLL), TuesPechkin... Tôi đã thử qua 1 số thư viện và nhận thấy:
Hôm nay mình sẽ hướng dẫn chuyển 1 page html đơn giản bằng TuesPechkin.
Gõ: "Install-Package TuesPechkin" để cài đặt TuesPechkin.
Bước 3:
- iTextSharp: hỗ trợ html không tốt, hay gặp lỗi khi sử dụng thẻ <ul>, </html> (hay code của mình viết thiếu gì nhỉ :D).
- WkHtmlToPdf: xuất file pdf từ html rất tốt nhưng có vấn đề nếu dự án là website
- Prince: hỗ trợ javascript rất tốt nhưng đây là thư viện có tính phí bản quyền.
- Pechkin: có 1 số vấn đề khi build và deploy website
- TuesPechkin: khá ít tài liệu nhưng đây là 1 thư viện miễn phí khá tốt để chuyển html sang pdf.
Hôm nay mình sẽ hướng dẫn chuyển 1 page html đơn giản bằng TuesPechkin.
Cài đặt
Mở Package Console ManagerGõ: "Install-Package TuesPechkin" để cài đặt TuesPechkin.
Chuyển đổi nhanh tài liệu Html
IPechkin converter = Factory.Create();
byte[] result = converter.Convert("Lorem ipsum wampum");
Chuyển đổi từ nguồn Html string
- Chuyển View và Master Layout thành chuỗi string
- Chuyển đường dẫn tương đối thành đường dẫn tuyệt đối.
- Gọi TuesPechkin để thực hiện việc chuyển đổi.
protected string RenderViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, "_Layout");
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Bước 2: (Bạn tự implement)Bước 3:
public ActionResult ConfigurePdfSettings()
{
var html = RenderViewToString("Index", null);
html = ConvertRelativePathsToAbsolute(html, "http://yourUrl/");
var document = new HtmlToPdfDocument
{
GlobalSettings =
{
ProduceOutline = true,
DocumentTitle = "Pretty Websites",
PaperSize = PaperKind.A4, // Implicit conversion to PechkinPaperSize
Margins =
{
//All = 1.375,
Unit = Unit.Centimeters
}
},
Objects = {
new ObjectSettings { HtmlText = html }
}
};
// create converter
IPechkin converter = Factory.Create();
converter.Error += new TuesPechkin.EventHandlers.ErrorEventHandler(delegate(IPechkin ip, string s)
{
Debugger.Log(1, "Convert PDF", s);
});
// convert document
byte[] result = converter.Convert(document);
return File(result, System.Net.Mime.MediaTypeNames.Application.Octet, "test.pdf");
}
Chúc các bạn thành công
Nhận xét
Đăng nhận xét