Reputation: 5851
I am trying to create pdf in asp.net core using Rotativa but it throw me an error. I want to create html and convert it to pdf and then store in on server directory
[HttpPost]
public IActionResult Index(Invoice invoice)
{
var webRoot = _env.WebRootPath;
var pdf = new ViewAsPdf("Index")
{
FileName = "Test.pdf",
PageSize = Rotativa.AspNetCore.Options.Size.A4,
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
PageHeight = 20,
};
var byteArray = pdf.BuildFile(ControllerContext).Result;
//var fileStream = new MemoryStream(Path.Combine(webRoot, pdf.FileName), FileMode.Create, FileAccess.Write);
var memoryStream = new MemoryStream(byteArray, 0, byteArray.Length);
}
Upvotes: 2
Views: 1401
Reputation: 141452
The error indicates that you haven't configured Rotativa.
Configuration your application like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
Rotativa.AspNetCore.RotativaConfiguration.Setup(env);
}
Also add wkhtmltopdf.exe
to wwwroot like this:
wwwroot
Rotativa
wkhtmltopdf.exe
Once you have done that, the following will work.
public async Task<IActionResult> Index()
{
var pdf = new Rotativa.AspNetCore.ViewAsPdf("Index")
{
FileName = "C:\\Test.pdf",
PageSize = Rotativa.AspNetCore.Options.Size.A4,
PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait,
PageHeight = 20,
};
var byteArray = await pdf.BuildFile(ControllerContext);
return File(byteArray, "application/pdf");
}
Note the use of async/await
instead of using .Result
.
Needs Configuration section here https://github.com/webgio/Rotativa.AspNetCore
GitHub demo here https://github.com/shaunluttin/asp-net-core-rotativa-pdf
Download of wkhtmltopdf here https://wkhtmltopdf.org/
Upvotes: 5