如何在C#中将数据从视图导出到PDF?

时间:2018-09-20 19:51:00

标签: c# pdf

到目前为止,这是我的代码。我正在尝试从视图中获取显示详细信息到PDF文档中

public class PdfResult : PartialViewResult 
{
    // Setting a FileDownloadName downloads the PDF instead of viewing it
    public string FileDownloadName { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        // Set the model and data
        context.Controller.ViewData.Model = Model;
        ViewData = context.Controller.ViewData;
        TempData = context.Controller.TempData;

        // Get the view name
        if (string.IsNullOrEmpty(ViewName))
        {
            ViewName = context.RouteData.GetRequiredString("action");    
        }

        // Get the view
        ViewEngineResult viewEngineResult = null;
        if (View == null)
        {
            viewEngineResult = FindView(context);
            View = viewEngineResult.View;
        }

        // Render the view
        StringBuilder sb = new StringBuilder();
        using (TextWriter tr = new StringWriter(sb))
        {
            ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, tr);
            View.Render(viewContext, tr);    
        }
        if (viewEngineResult != null)
        {
            viewEngineResult.ViewEngine.ReleaseView(context, View);
        }

        // Create a PDF from the rendered view content
        Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf();
        using (MemoryStream ms = new     MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())))
        {
            pdf.BindXML(ms, null);
        }

        // Save the PDF to the response stream
        using(MemoryStream ms = new MemoryStream())
        {
            pdf.Save(ms);
            FileContentResult result = new FileContentResult(ms.ToArray(), "application/pdf")
            {
                FileDownloadName = FileDownloadName
            };
            result.ExecuteResult(context);
        }
    }
}

是否有更简单的方法导出为PDF?

0 个答案:

没有答案