I’ve developed a library that lets you use rotativa.io to create PDF files using Razor templates without requiring you to reference Asp.Net Core libraries. This makes it suitable to be used in console applications or Azure Functions (since it uses a HTTP call to build the PDF it will work even if on a Consumption Plan). Of course you can also use this in a Asp.Net Core MVC, WebApi or Razor Pages app.
You’ll need a valid rotativa.io account. You can grab a (limited) free account or subscribe to a paid plan.
Usage is dead simple:
Install the Nuget package
Install-package RotativaIO.NetCore
Create a new PdfHelper
object passing your account’s ApiKey and your chosen endpoint. Then you can use one of the helper’s async methods to create PDF files. In the following example we are using GetPdfAsByteArray
passing as parameters:
-
template: a string containing a Razor template, this can be read out of a local file, a file in a cloud storage, a string stored in a DB, or any other storage system.
-
model: an object containing properties referenced in the template. This can be a complex object containing collections and other objects. In the template you can use all the Razor syntax capabilities (if, for loop etc.) to render all the information contained in the model.
-
a RotativaOptions object with all the same parameters you can use with Rotativa views.
var template = "Hello @Model.Name";
var model = new TestModel { Name = "Giorgio" };
using (var pdfHelper = new PdfHelper(rotativaioKey, "https://eunorth.rotativahq.com"))
{
var pdfBytes = await pdfHelper.GetPdfAsByteArray(
template,
model,
new RotativaOptions
{
PageSize = Size.A5
});
/// do something with it, like, for example, send the PDF via email
}
The source code for the library is available at GitHub, where you can find a code example in the included demo Azure function project.