Microsoft Edge在ASP.NET Core中将HTML导出为PDF的问题

时间:2017-07-29 16:03:56

标签: pdf-generation asp.net-core-mvc microsoft-edge html-to-pdf jsreport

我正在尝试在 ASP.Net Core Web 项目中从Html生成pdf。我在网上找不到这方面的内容。大多数软件包都没有为asp.net核心做好准备。浏览了几天后,我找到了this How to export HTML to PDF in ASP.NET Core

我已经下载了项目

  

导出为pdf在chrome上完美运行,但在 Edge 上无效;它从未完成出口。

Edge和pdf是否有任何问题我没有在node.js上做太多工作,所以不确定出了什么问题。任何帮助将受到高度赞赏。在这里,我还添加了pdf.js的代码

module.exports = function (callback, html) { 
    var jsreport = require('jsreport-core')(); 

    jsreport.init().then(function () { 
        return jsreport.render({ 
            template: { 
                content: html, 
                engine: 'jsrender', 
                recipe: 'phantom-pdf' 
            } 
        }).then(function (resp) { 
            callback(null, resp.content.toJSON().data); 
        }); 
    }).catch(function (e) { 
        callback(e, null); 
    }) 
}; 

nodejs的package.json

{ 
  "name": "pdf", 
  "version": "1.0.0", 
  "description": "", 
  "main": "index.js", 
  "dependencies": { 
    "jsreport-core": "^1.3.1", 
    "jsreport-phantom-pdf": "^1.4.4", 
    "jsreport-jsrender": "^1.0.2" 
  }, 
  "devDependencies": {}, 
  "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1" 
  }, 
  "author": "", 
  "license": "ISC" 
} 

更新

@Martin Beeby在Controller代码上找到问题。以下代码不适用于MS Edge

public class HomeController : Controller
{
    [HttpGet]
    public async Task<IActionResult> Index([FromServices] INodeServices nodeServices)
    {
        HttpClient hc = new HttpClient();
        var htmlContent = await hc.GetStringAsync($"http://{Request.Host}/report.html");

        var result = await nodeServices.InvokeAsync<byte[]>("./pdf", htmlContent);

        HttpContext.Response.ContentType = "application/pdf";

        HttpContext.Response.Headers.Add("x-filename", "report.pdf");
        HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "x-filename");
        HttpContext.Response.Body.Write(result, 0, result.Length);
        return new ContentResult();
    }
}

1 个答案:

答案 0 :(得分:1)

如果您将控制器代码更改为:

public async Task<IActionResult> Index([FromServices] INodeServices nodeServices)
{
    HttpClient hc = new HttpClient();
    var htmlContent = await hc.GetStringAsync($"http://{Request.Host}/report.html");

    var result = await nodeServices.InvokeAsync<byte[]>("./pdf", htmlContent);

    return File(result, "application/pdf", "report.pdf");
}

然后它适用于Chrome并提示在Edge中下载。