How to Render an ASP.NET MVC View in PDF Format

How to render an ASP.NET MVC View in PDF format

You might be able to tap into the Response during OnResultExecuting and replace the Filter property with something that stores the resultant HTML in a MemoryStream. Then you could clear the Response during OnResultExecuted and replace it with the results of your PDF conversion. I'm not sure that this would be better than just getting the HTML from the URL, though.

 public FileStreamResult Print(int id)
{
var model = _CustomRepository.Get(id);
this.ConvertToPDF = true;
return View( "HtmlView" );
}

public override OnResultExecuting( ResultExecutingContext context )
{
if (this.ConvertToPDF)
{
this.PDFStream = new MemoryStream();
context.HttpContext.Response.Filter = new PDFStreamFilter( this.PDFStream );
}
}

public override OnResultExecuted( ResultExecutedContext context )
{
if (this.ConvertToPDF)
{
context.HttpContext.Response.Clear();
this.PDFStream.Seek( 0, SeekOrigin.Begin );
Stream byteStream = _PrintService.PrintToPDF( this.PDFStream );
StreamReader reader = new StreamReader( byteStream );
context.HttpContext.Response.AddHeader( "content-disposition",
"attachment; filename=report.pdf" );
context.HttpContext.Response.AddHeader( "content-type",
"application/pdf" );
context.HttpContext.Response.Write( reader.ReadToEnd() );
}
}

The PDFStreamFilter would need to override the "Write" method(s) and send the data to the memory stream instead.

Asp.Net MVC how to get view to generate PDF

our final answer to this problem was to use Rotativa.

It wraps up the WKhtmltopdf.exe like some of the other solutions, but it's by far the easiest to use that I have found

I went and up voted all the other answers that also solve the problem well, but this is what we used to solve the problem posed in the question above. It is different from the other answers.

Here is a Rotativa Tutorial.

after you install it, this is all your need

public ActionResult PrintInvoice(int invoiceId)
{
return new ActionAsPdf(
"Invoice",
new { invoiceId= invoiceId })
{ FileName = "Invoice.pdf" };
}

Very Very simple.

ASP.NET MVC Render View to PDF File and save on disk

I've used WkHtmlToPdf before with good success.

It's a command line tool that you can install on your server.

ASP.Net MVC 5 Render PDF in Browser from Byte[] C#

Update:

PDF needs to be embeded in the HTML with <embed> or <iframe> . You could also use library such as pdf.js to render pdf files with some controls.

The pdf.js readme has samples and how to: https://github.com/mozilla/pdf.js


You can return the pdf as file by passing the binary using retun File() method

public ActionResult GetRxPdf(int prescriptionId)
{
var retVal = _service.GetRxPdf(prescriptionId);
byte[] byteArray = retVal.FileData;
return File(byteArray , "application/pdf" , "Filename.pdf");
}

How to view PDF document in MVC and not download it directly?

You have to set the Content-Disposition header on the response to inline

public FileResult GetHTMLPageAsPDF(long empID) {
string htmlPagePath = "anypath...";
// convert html page to pdf
PageToPDF obj_PageToPDF = new PageToPDF();
byte[] databytes = obj_PageToPDF.ConvertURLToPDF(htmlPagePath);

//return resulted pdf document
var contentLength = databytes.Length;
Response.AppendHeader("Content-Length", contentLength.ToString());
//Content-Disposition header set to inline along with file name for download
Response.AppendHeader("Content-Disposition", "inline; filename=" + empID + ".pdf");

return File(databytes, "application/pdf;");
}

The browser will interpret the headers and display the file directly in the browser provided it has the capability to do so, either built in or via plugin.

How do I generate a PDF of my MVC view after styles and scripts applied

Razor/ASP.Net will only generate source, not execute client-side scripts. You need to use something that emulates a web browser to turn the client-side script into a rendered PDF.

That means it needs to understand both script and styling (i.e. just like a browser).

There are several commercial products out there, but I have personally used Essential Objects PDF converter to generate views direct to PDF. It has a built-in Javascript engine, so looks just like it will in the browser.

Please note these products are very complex (as they include complete Browser rendering engines), so most will required paid licences (for commercial use at least).

Source :
How to generate PDF from HTML view after scripts and styles applied in ASP.NET MVC

TO GENERATE PDF AFTER SCRIPTS AND STYLES RENDERED

Best Tool for generating javascript and styles rendered views or html pages is phantomJS.

Download the .exe file with the rasterize.js function found in root of exe of example folder and put inside solution.

Following code generate PDF File :

public ActionResult DownloadHighChartHtml()
{
string serverPath = Server.MapPath("~/phantomjs/");
string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";
string Url = "http://stagebelweb.azurewebsites.net/race/16867";

new Thread(new ParameterizedThreadStart(x =>
{
ExecuteCommand(string.Format("cd {0} & E: & phantomjs rasterize.js {1} {2} \"A4\"", serverPath, Url, filename));
//E: is the drive for server.mappath
})).Start();

var filePath = Path.Combine(Server.MapPath("~/phantomjs/"), filename);

var stream = new MemoryStream();
byte[] bytes = DoWhile(filePath);

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Image.pdf");
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.End();
return RedirectToAction("HighChart");
}

private void ExecuteCommand(string Command)
{
try
{
ProcessStartInfo ProcessInfo;
Process Process;

ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);

ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;

Process = Process.Start(ProcessInfo);
}
catch { }
}

private byte[] DoWhile(string filePath)
{
byte[] bytes = new byte[0];
bool fail = true;

while (fail)
{
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
}

fail = false;
}
catch
{
Thread.Sleep(1000);
}
}

System.IO.File.Delete(filePath);
return bytes;
}

Saving an MVC View to PDF

To render a non-static page to a pdf, you need to render the page to a string, using a ViewModel, and then convert to a pdf:

Firstly, create a method RenderViewToString in a static class, that can be referenced in a Controller:

public static class StringUtilities
{
public static string RenderViewToString(ControllerContext context, string viewPath, object model = null, bool partial = false)
{
// first find the ViewEngine for this view
ViewEngineResult viewEngineResult = null;
if (partial)
{
viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
}
else
{
viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
}

if (viewEngineResult == null)
{
throw new FileNotFoundException("View cannot be found.");
}

// get the view and attach the model to view data
var view = viewEngineResult.View;
context.Controller.ViewData.Model = model;

string result = null;

using (var sw = new StringWriter())
{
var ctx = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, sw);
view.Render(ctx, sw);
result = sw.ToString();
}

return result.Trim();
}
}

Then, in your Controller:

var viewModel = new YourViewModelName
{
// Assign ViewModel values
}

// Render the View to a string using the Method defined above
var viewToString = StringUtilities.RenderViewToString(ControllerContext, "~/Views/PathToView/ViewToRender.cshtml", viewModel, true);

You then have the view, generated by a ViewModel, as a string that can be converted to a pdf, using one of the libraries out there.

Hope it helps, or at least sets you on the way.

MVC - Store PDF in view model and embed in view?

It's possible, but you may get inconsistent results depending on the browser.

In your first example, you aren't actually embedding anything. You're emitting an <EMBED> tag with the location of the PDF; the browser is actually responsible for retrieving the PDF (in a separate HTTP request). So while there is a PDF embedded on the final page, it is not embedded in the HTTP response.

If you want to embed something so that the binary content appears inline in the HTML document, you'd follow this sort of syntax:

<EMBED Src="data:application/pdf;base64,[Based64-encoded string]">

So if @Model.file is a byte array containing the file, you can accomplish what you want by adding a new property to the model that returns the markup, like so:

class MyModel
{
public string InlineMarkup
{
get
{
return String.Format("data:application/pdf;base64,{0}", Convert.ToBase64String(this.file));
}
}

...and in your view:

<embed src="@Model.InlineMarkup" width="100% " height="100%" type="application/pdf">

Note also that EMBED is a void element, so the </EMBED> tag is not needed and not strictly legal.

See also this question.



Related Topics



Leave a reply



Submit