加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 00:19:59 所属栏目:asp.Net 来源:网络整理
导读:我想将一段html导出为pdf文件,但我没有任何兼容的nuget包。 当我尝试安装任何人时:“X与netcoreapp1.0不兼容(.NETCoreApp,Version = v1.0)。” 有谁知道使用asp.net核心导出到pdf的任何方法? 非常感谢提前! 解决方法 从我原来的答案复制到 Export to pd
我想将一段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

我没有尝试过这些。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读