I wanted to get all student information in tabular format so i created appropriate view. Now can i make a pdf report of that view(By passing that view to any action) which will look exactly as view is looking???
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Short answer is not easily, you can use iTextSharp (available on NuGet) and try the following:
public EmptyResult CreatePdf()
{
var document = new Document(PageSize.A4, 50, 50, 25, 25);
// Create a new PdfWriter object, specifying the output stream
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
// Open the Document for writing
document.Open();
var html = RenderRazorViewToString("PdfView", pdfViewModel);
var worker = new HTMLWorker(document);
var css = new StyleSheet();
css.LoadTagStyle(HtmlTags.TH, HtmlTags.BGCOLOR, "#616161");
css.LoadTagStyle(HtmlTags.TH, HtmlTags.COLOR, "#fff");
css.LoadTagStyle(HtmlTags.BODY, HtmlTags.FONT, "verdana");
css.LoadTagStyle(HtmlTags.TH, HtmlTags.FONTWEIGHT, "bold");
css.LoadStyle("even", "bgcolor", "#EEE");
worker.SetStyleSheet(css);
var stringReader = new StringReader(html);
worker.Parse(stringReader);
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "PdfView.pdf");
Response.BinaryWrite(output.ToArray());
return new EmptyResult();
}
private string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
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();
}
}
You will need to fiddle with the styles and the resultant Html to get it to work with the HtmlWorker tho.
HTH
Si