Export html to pdf in ASP.NET Core
I want to export a piece of html to a pdf file but i do not any compatible nuget package.
When I try to install anyone: "X not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0)."
Does anyone know any way to export to a pdf using asp.net core??
You can use jsreport .net sdk if you are in .net core 2.0 also without more complex node services. This includes among other features filters to convert your existing razor views into pdf. From the docs:
1. Install nugets jsreport.Binary, jsreport.Local and jsreport.AspNetCore
2.
In you Startup.cs
configure it as the following
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddJsReport(new LocalReporting()
.UseBinary(JsReportBinary.GetBinary())
.AsUtility()
.Create());
}
3.
Then you need to add MiddlewareFilter
attribute to the particular action and specify which conversion you want to use. In this case html to pdf conversion.
[MiddlewareFilter(typeof(JsReportPipeline))]
public IActionResult Invoice()
{
HttpContext.JsReportFeature().Recipe(Recipe.ChromePdf);
return View();
}
You can reach bunch of other options for headers, footers or page layout on JsReportFeature()
. Note that the same way you can also produce excel files from html. See more information in the documentation.
PS: I'm the author of jsreport.
Copied from my original answer here Export to pdf using ASP.NET 5:
One way to generate pdf from html in .NET Core (without any .NET framework dependencies) is using Node.js from within the .NET Core application. The following example shows how to implement an HTML to PDF converter in a clean ASP.NET Core Web Application project (Web API template).
Install the NuGet package Microsoft.AspNetCore.NodeServices
In Startup.cs add the line services.AddNodeServices()
like this
public void ConfigureServices(IServiceCollection services)
{
// ... all your existing configuration is here ...
// Enable Node Services
services.AddNodeServices();
}
Now install the required Node.js packages:
From the command line change working directory to the root of the .NET Core project and run these commands.
npm init
and follow the instructions to create the package.json file
npm install jsreport-core --save
npm install jsreport-jsrender --save
npm install jsreport-phantom-pdf --save
Create a file pdf.js
in the root of the project containing
module.exports = function (callback) {
var jsreport = require('jsreport-core')();
jsreport.init().then(function () {
return jsreport.render({
template: {
content: '<h1>Hello {{:foo}}</h1>',
engine: 'jsrender',
recipe: 'phantom-pdf'
},
data: {
foo: "world"
}
}).then(function (resp) {
callback(/* error */ null, resp.content.toJSON().data);
});
}).catch(function (e) {
callback(/* error */ e, null);
})
};
Have a look here for more explanation on jsreport-core
.
Now create an action in an Mvc controller that calls this Node.js script
[HttpGet]
public async Task<IActionResult> MyAction([FromServices] INodeServices nodeServices)
{
var result = await nodeServices.InvokeAsync<byte[]>("./pdf");
HttpContext.Response.ContentType = "application/pdf";
string filename = @"report.pdf";
HttpContext.Response.Headers.Add("x-filename", filename);
HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "x-filename");
HttpContext.Response.Body.Write(result, 0, result.Length);
return new ContentResult();
}
Off course you can do whatever you want with the byte[]
returned from nodeServices, in this example I'm just outputting it from a controller action so it can be viewed in the browser.
You could also exchange the data between Node.js and .NET Core by a base64 encoded string using resp.content.toString('base64')
in pdf.js
and use
var result = await nodeServices.InvokeAsync<byte[]>("./pdf");
in the action and then decode the base64 encoded string.
Alternatives
Most pdf generator solutions still depend on .NET 4.5/4.6 framework. But there seems to be some paid alternatives available if you don't like to use Node.js:
- NReco.PdfGenerator.LT
- EVO HTML to PDF Converter Client for .NET Core
- Winnovative HTML to PDF Converter Client for .NET Core
I haven't tried any of these though.
I hope we will soon see some open source progress in this area.
You can check DinkToPdf library. It is a wrapper around wkhtmltopdf library for .NET Core.
Synchronized converter
Use this converter in multi threaded applications and web servers. Conversion tasks are saved to blocking collection and executed on a single thread.
var converter = new SynchronizedConverter(new PdfTools());
Define document to convert
var doc = new HtmlToPdfDocument()
{
GlobalSettings = {
ColorMode = ColorMode.Color,
Orientation = Orientation.Landscape,
PaperSize = PaperKind.A4Plus,
},
Objects = {
new ObjectSettings() {
PagesCount = true,
HtmlContent = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In consectetur mauris eget ultrices iaculis. Ut odio viverra, molestie lectus nec, venenatis turpis.",
WebSettings = { DefaultEncoding = "utf-8" },
HeaderSettings = { FontSize = 9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
}
}
};
I was having the same issue! I wanted to generate PDF files from HTML strings. I then came across PhantomJs which is a command line utility for converting html files to pdf. I wrote a cross-platform wrapper over it in C# for .NET CORE and its working great on Linux! Though as of now its only for 64-bit Linux, because that is the only platform .NET Core Supports currently. The project can be found here
PhantomJs.NetCore.PdfGenerator gen = new PhantomJs.NetCore.PdfGenerator("/path/to/pantomjsfolder");
string outputFilePath = gen.GeneratePdf("<h1>Hello</h1>","/folder/to/write/file/in");