ASP.NET MVCで利用する
基本方針
- PartialViewで指定したHTML(PDFに変換する)をstringにする。(RenderRazorViewToString)
- HTMLストリングをiTextSharpに渡してPDFのバイトコードにする。(HtmlToPdf)
- PDFのバイトコードをコントローラーでレスポンスにする。
コード
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
string result = Utils.RenderRazorViewToString(this, "TestPartialView", null);
var buffer = HtmlToPdf.ConvertHtmlToMemory(result);
return File(buffer, "application/pdf", "test1.pdf");
}
}
RenderRazorViewToString
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
public class HtmlToPdf
{
public static byte[] ConvertHtmlToMemory(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);
}
}
参考