1
MVC ActionResult view directly to a PDF
Question asked by Jack Hughes - 2/17/2018 at 10:08 AM
Answered
We have an MVC 5 ActionResult that creates a partial view. We would like to convert that partial view to a PDF. Can Document Ultimate do that?

3 Replies

Reply to Thread
0
Cem Alacayir Replied
Employee Post
Hi,
Yes you can do that with DocumentUltimate, please see this example.
 
You can render the component in a PartialView and use AJAX to update/replace it. In your main view call RenderHead and in your partial view call RenderBody. Share model creating code in your controller between main and partial views so that you can pass same model to both views.
0
Cem Alacayir Replied
Employee Post
By the way if you meant to convert some document to PDF and then return that PDF file directly you can do this:
 
public ActionResult DownloadPdf()
{
	var inputFile = "SomeDocument.docx";

	var outputStream = new MemoryStream();

	var documentConverter = new DocumentConverter(inputFile);
	documentConverter.ConvertTo(outputStream, DocumentFormat.Pdf);

	//Rewind the stream which contains the converted Pdf now.
	outputStream.Position = 0;

	return File(
		outputStream,
		System.Net.Mime.MediaTypeNames.Application.Pdf, 
		"Result.pdf");
}
 
0
Cem Alacayir Replied
Employee Post Marked As Answer
If you meant to convert  the HTML result of your partial view to PDF, then use this:
 
public ActionResult SomeAction()
{
    //Call your existing partial view and convert it to string
    var html = RenderToString(PartialView("SomeView"));

    var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(html));
    var outputStream = new MemoryStream();

    var documentConverter = new DocumentConverter(inputStream, DocumentFormat.Html);
    documentConverter.ConvertTo(outputStream, DocumentFormat.Pdf);

    //Rewind the stream which contains the converted Pdf now.
    outputStream.Position = 0;

    return File(
        outputStream,
        System.Net.Mime.MediaTypeNames.Application.Pdf,
        "Result.pdf");
}

private string RenderToString(PartialViewResult partialView)
{
    var rc = Request.RequestContext;
    var controllerName = rc.RouteData.Values["controller"].ToString();

    var controller = (ControllerBase)ControllerBuilder.Current
        .GetControllerFactory().CreateController(rc, controllerName);

    var controllerContext = new ControllerContext(rc, controller);

    var view = ViewEngines.Engines.FindPartialView(controllerContext, partialView.ViewName).View;

    var sb = new StringBuilder();

    using (var sw = new StringWriter(sb))
    using (var tw = new HtmlTextWriter(sw))
    {
        view.Render(
            new ViewContext(controllerContext, view, partialView.ViewData, partialView.TempData, tw),
            tw
        );
    }

    return sb.ToString();
}
 

Reply to Thread