Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 956
Carlos Avatar asked Sep 07 '16 08:09

Carlos


People also ask

What is NReco?

NReco Query Builder is a javascript widget for building complex data filters. ASP.NET integration provides backend that translates UI widget state into SQL or MongoDb query.


Video Answer


2 Answers

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.

like image 134
Jan Blaha Avatar answered Oct 12 '22 05:10

Jan Blaha


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.

like image 23
Sjolund Avatar answered Oct 12 '22 03:10

Sjolund