从我原来的答案复制到
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: '
Hello {{:foo}}
',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 MyAction([FromServices] INodeServices nodeServices)
{
var result = await nodeServices.InvokeAsync("./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
我没有尝试过这些。
我希望我们很快会看到这一领域的一些开源进展。