How to make a pdf report of a particular view in m

2019-04-16 17:31发布

问题:

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