I'm looking for a good way to save an MVC ActionResult to a byte array (file). Reason for this is that I'm using Rotativa to convert a HTML View to a PDF. That works nicely and returns my user with the PDF in the browser. Now I want to send an e-mail from the server, including that same PDF as an attachment. For sending e-mail I'm using the ActionMailer.Net nuget package. That has the option of including byte arrays as attachments.
So I need to pass a byte array with my PDF file to the send mail method. But the action returning the PDF has ActionResult as returntype, not FileStreamResult (unfortunately). I don't exactly know why this choice was made, but that's what it is.
The Rotativa package uses Wkhtmltopdf to convert the HTML. I guess I could implement that myself, but that seems kinda pointless since I already have a method which returns exactly what I need; I just need a way to get that result into a byte array.
You can inherit 'ViewAsPdf' and create a method to call some protected methods of 'ViewAsPdf':
public class ViewAsPdf2 : ViewAsPdf
{
public ViewAsPdf2(string viewName, object model) : base(viewName, model) { }
public byte[] GetByte(ControllerContext context)
{
base.PrepareResponse(context.HttpContext.Response);
base.ExecuteResult(context);
return base.CallTheDriver(context);
}
}
And in your action:
var pdf = new ViewAsPdf2("MyView", model);
var pdfByteArray = pdf.GetByte(ControllerContext);
SendEmail(pdfByteArray);
return null;
So you can use the byte[] to do what you want and the return will be the PDF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With