asp.net-core – 在ASP.NET Core中将html导出为pdf

前端之家收集整理的这篇文章主要介绍了asp.net-core – 在ASP.NET Core中将html导出为pdf前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将一段html导出为pdf文件,但我没有任何兼容的nuget包。

当我尝试安装任何人时:“X与netcoreapp1.0不兼容(.NETCoreApp,Version = v1.0)。”

有谁知道使用asp.net核心导出到pdf的任何方法

非常感谢提前!

解决方法

从我原来的答案复制到 Export to pdf using ASP.NET 5

从.NET Core中的html生成pdf(没有任何.NET框架依赖性)的一种方法是在.NET Core应用程序中使用Node.js。
以下示例说明如何在干净的ASP.NET Core Web Application项目(Web API模板)中实现HTML到PDF转换器。

安装NuGet包Microsoft.AspNetCore.NodeServices

在Startup.cs中添加像这样的service.AddNodeServices()行

public void ConfigureServices(IServiceCollection services)
{
    // ... all your existing configuration is here ...

    // Enable Node Services
    services.AddNodeServices();
}

现在安装所需的Node.js包:

从命令行将工作目录更改为.NET Core项目的根目录并运行这些命令。

npm init

并按照说明创建package.json文件

npm install jsreport-core --save
npm install jsreport-jsrender --save
npm install jsreport-phantom-pdf --save

在包含的项目的根目录中创建文件pdf.js.

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);
    })
};

看看here有关jsreport-core的更多解释。

现在在调用此Node.js脚本的Mvc控制器中创建一个操作

[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,result.Length);
    return new ContentResult();
}

当然,您可以使用nodeServices返回的byte []执行任何操作,在此示例中,我只是从控制器操作中输出它,以便可以在浏览器中查看它。

您还可以使用pdf.js中的resp.content.toString(‘base64’)通过base64编码的字符串在Node.js和.NET Core之间交换数据并使用
var result = await nodeServices.InvokeAsync< byte []>(“./ pdf”);在动作中然后解码base64编码的字符串。

备择方案

大多数pdf生成解决方案仍然依赖于.NET 4.5 / 4.6框架。但是,如果您不喜欢使用Node.js,似乎有一些付费替代方案:

> NReco.PdfGenerator.LT
>用于.NET Core的EVO HTML到PDF转换器客户端
>用于.NET Core的Winnovative HTML to PDF Converter Client

我没有尝试过这些。

我希望我们很快会看到这一领域的一些开源进展。

原文链接:https://www.f2er.com/netcore/252010.html

猜你在找的.NET Core相关文章