* ASP.NET MVCで利用する [#h4b04034]
** 基本方針 [#se9bc264]
- PartialViewで指定したHTML(PDFに変換する)をstringにする。(RenderRazorViewToString)
- HTMLストリングをiTextSharpに渡してPDFのバイトコードにする。(HtmlToPdf)
- PDFのバイトコードをコントローラーでレスポンスにする。
** コード [#xb72b48f]
*** Controller [#de1fe381]
public class HomeController : Controller
{
public ActionResult Index()
{
string result = Utils.RenderRazorViewToString(this, "TestPartialView", null);
var buffer = HtmlToPdf.ConvertHtmlToMemory(result);
var buffer = HtmlToPdf.ConvertHtmlToPdf(result);
return File(buffer, "application/pdf", "test1.pdf");
}
}
*** RenderRazorViewToString [#e5675441]
public static class Utils
{
public static string RenderRazorViewToString(this Controller controller, string viewName, object model)
{
controller.ViewData.Model = model;
using (var sw = new StringWriter()) {
var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
}
*** HtmlToPdf [#z9faf5c1]
public class HtmlToPdf
{
public static byte[] ConvertHtmlToMemory(string html)
public static byte[] ConvertHtmlToPdf(string html)
{
MemoryStream output = new MemoryStream();
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
HTMLWorker worker = new HTMLWorker(document);
var provider = new Dictionary<string, object>() {
{ HTMLWorker.FONT_PROVIDER, new MyFontProvider() }
};
worker.SetProviders(provider);
PdfWriter writer = PdfWriter.GetInstance(document, output);
writer.CloseStream = false;
document.Open();
worker.StartDocument();
TextReader reader = new StringReader(html);
worker.Parse(reader);
worker.EndDocument();
worker.Close();
document.Close();
return output.ToArray();
}
}
public class MyFontProvider : FontFactoryImp
{
public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
{
if (string.IsNullOrEmpty(fontname)) {
fontname = "c:\\windows\\fonts\\msmincho.ttc,0";
encoding = BaseFont.IDENTITY_H;
embedded = BaseFont.EMBEDDED;
}
return base.GetFont(fontname, encoding, embedded, size, style, color, cached);
}
}
** 参考 [#xf972c61]
- http://www.codeproject.com/Articles/66948/Rendering-PDF-views-in-ASP-MVC-using-iTextSharp
- http://forums.asp.net/t/1889126.aspx?How+to+insert+Document+NewPage+into+iTextSharp+at+position
- http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3
- http://stackoverflow.com/questions/16975657/download-pdf-in-asp-mvc
- http://stackoverflow.com/questions/2822843/itextsharp-html-to-pdf