我正在开发 MVC 6 应用程序(DNX Core 5.0 框架)。不幸的是,我没有找到任何用于 pdf 导出的库。
任何帮助将不胜感激。
最佳答案
我终于找到了一种从 .NET Core 生成 pdf 的方法(没有任何 .NET 框架依赖项),即在我的 .NET Core 应用程序中使用 Node.js。 以下示例演示如何在干净的 ASP.NET Core Web 应用程序项目(Web API 模板)中实现 HTML 到 PDF 转换器。
安装 NuGet 包 Microsoft.AspNetCore.NodeServices
在 Startup.cs 中添加行 services.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
的更多说明.
现在在 Mvc Controller 中创建一个调用此 Node.js 脚本的操作
[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();
}
当然,您可以使用byte[]
做任何您想做的事情。从 nodeServices 返回,在本例中,我只是从 Controller 操作中输出它,以便可以在浏览器中查看它。
您还可以使用resp.content.toString('base64')
通过base64编码字符串在Node.js和.NET Core之间交换数据。在pdf.js
并使用
var result = await nodeServices.InvokeAsync<byte[]>("./pdf");
在操作中,然后解码 Base64 编码的字符串。
大多数 pdf 生成器解决方案仍然依赖于 .NET 4.5/4.6 框架。 上面的两个答案(JsReport 和 RazorPDFCore)都不适用于 .NET Core。
如果您不喜欢使用 Node.js,似乎可以使用一些付费替代方案:
- NReco.PdfGenerator.LT
- 适用于 .NET Core 的 EVO HTML 到 PDF 转换器客户端
- 适用于 .NET Core 的 Winnovative HTML 到 PDF 转换器客户端
不过我还没有尝试过这些。
我希望我们很快就能看到该领域的一些开源进展。
关于asp.net-core - 使用 ASP.NET 5 导出为 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36983300/