JsReport .NET Core - 从url生成PDF

时间:2018-03-12 18:10:19

标签: pdf asp.net-core jsreport

尝试使用JsReport从url生成pdf,但在github repo中找不到任何文档或示例。

基本上我需要生成pdf并将其附加到电子邮件中,并且我设法将数据作为byte []返回,但我似乎无法弄清楚如何使用现有的View / Action。 / p>

这是生成PDF以供查看的操作...

[MiddlewareFilter(typeof(JsReportPipeline))]
    public async Task<IActionResult> Pdf(Guid id)
    {
        var serviceOrder = await _serviceOrderService.Get(id);
        if (serviceOrder == null) return new NotFoundResult();

        var model = _mapper.Map<ServiceOrderModel>(serviceOrder);
        HttpContext.JsReportFeature().Recipe(Recipe.PhantomPdf);
        return View(model);
    }

此操作应从“详细信息”中获取pdf视图,并生成我可以附加的PDF。下面我可以使用静态内容生成它,例如“Hello from pdf”,但我无法弄清楚如何在ASPNET Core中使用我的“详细信息”视图。

public async Task<IActionResult> Email(Guid id)
    {
        var rs = new LocalReporting().UseBinary(JsReportBinary.GetBinary()).AsUtility().Create();

        var report = await rs.RenderAsync(new RenderRequest()
        {
            Template = new Template()
            {
                Recipe = Recipe.PhantomPdf,
                Engine = Engine.None,
                Content = "Hello from pdf",
            }
        });

        var memoryStream = new MemoryStream();
        await report.Content.CopyToAsync(memoryStream);
        memoryStream.Seek(0, SeekOrigin.Begin);

        return new FileStreamResult(memoryStream, "application/pdf") { FileDownloadName = "out.pdf" };
    }

1 个答案:

答案 0 :(得分:1)

取自JsReport Github Dotnet Example

[MiddlewareFilter(typeof(JsReportPipeline))]
public IActionResult InvoiceDownload()
{
    HttpContext.JsReportFeature().Recipe(Recipe.ChromePdf)
        .OnAfterRender((r) => HttpContext.Response.Headers["Content-Disposition"] = "attachment; filename=\"myReport.pdf\"");

    return View("Invoice", InvoiceModel.Example());
}

如果要从Asp.net Core Controller Action方法返回文件,请尝试以下操作

[MiddlewareFilter(typeof(JsReportPipeline))]
public async Task<IActionResult> Pdf(Guid id)
{
    var serviceOrder = await _serviceOrderService.Get(id);
    if (serviceOrder == null) return new NotFoundResult();

    var model = _mapper.Map<ServiceOrderModel>(serviceOrder);
    HttpContext.JsReportFeature().Recipe(Recipe.PhantomPdf).OnAfterRender((r) =>
       HttpContext.Response.Headers["Content-Disposition"] = "attachment; filename=\"out.pdf\"");

    return View(model);
}