How to print PDF in ASP.NET MVC

Creating PDF docs in Asp.Net MVC is a fairly common functionality. Usually either for reporting or, more often, for having printable friendly documents.

I have tried the itextSharp with XMlWorkker but latest version is not free. We have to purchase it for commercial use.

After some research I have found the excellent wkhtmltopdf tool to convert html content to PDF. It uses the WebKit engine (used by browsers like Chrome and Safari) to render HTML. Its also fast.

With Rotativa, (It is using wkhtmltopdf) we can print the all things in pdf:

Steps to use Rotativa:

Install using the Nuget package manager or, more conveniently, with the package manager console, typing:

Install-Package Rotativa

Writing a controller action to return a view representing the desired PDF output.? Replace it with ActionAsPDF. Such as:

[csharp]
public ActionResult Test()??????? {
return new ActionAsPdf(“Index”, new { name = “Giorgio” }) { FileName = “Test.pdf” };
}
[/csharp]

More formats:

[csharp]
public ActionResult Test()
{
return new ActionAsPdf(“Index”, new { name = “Giorgio” }) { FileName = “Test.pdf” };
}

public ActionResult TestExternalUrl()
{
return new UrlAsPdf(“http://www.google.com”)
{
FileName = “TestExternalUrl.pdf”,
PageMargins = new Margins(0, 0, 0, 0)
};
}

public ActionResult TestView()
{
ViewBag.Message = string.Format(“Hello {0} to ASP.NET MVC!”, “Giorgio III.”);
return new ViewAsPdf(“Index”)
{
FileName = “TestView.pdf”,
PageSize = Size.A4,
PageOrientation = Orientation.Landscape,
PageMargins = { Left = 0, Right = 0 }
};
}

public ActionResult TestSaveOnServer(string fileName)
{
var filePath = Path.Combine(Server.MapPath(“/App_Data”), fileName);
ViewBag.Message = string.Format(“Hello {0} to ASP.NET MVC!”, “Giorgio III.”);
return new ViewAsPdf(“Index”)
{
FileName = fileName,
PageSize = Size.A3,
PageOrientation = Orientation.Landscape,
PageMargins = { Left = 0, Right = 0 },
SaveOnServerPath = filePath
};
}

public ActionResult TestViewWithModel(string id)
{
var model = new TestViewModel { DocTitle = id, DocContent = “This is a test” };
return new ViewAsPdf(model);
}

public ActionResult TestPartialViewWithModel(string id)
{
var model = new TestViewModel { DocTitle = id, DocContent = “This is a test with a partial view” };
return new PartialViewAsPdf(model);
}
[/csharp]


Posted

in

by

Tags: