jsreport / jsreport-dotnet-aspnetcore

Asp.net core and MVC support for jsreport c# sdk
MIT License
11 stars 8 forks source link

GeneratePDFAsync produce pdf 0kb #15

Closed dorathoto closed 4 years ago

dorathoto commented 4 years ago

at my startup:

      services.AddJsReport(new jsreport.Local.LocalReporting()
                .UseBinary(JsReportBinary.GetBinary())
                .AsUtility()
                .Create());
services.AddSingleton<IJsReportMVCService, JsReportMVCService>();

at my Controller:

public class TestController : Controller
{
public IJsReportMVCService JsReportMVCService { get; }
        public TestController (..., IJsReportMVCService jsReportMVCService)
        {
           JsReportMVCService = jsReportMVCService;
        }

public async Task<IActionResult> GerarPdf(){

                HttpContext.JsReportFeature()
                   .Recipe(Recipe.ChromePdf)
                   .Configure((r) => r.Template.Chrome = new Chrome
                   {
                       //  FooterTemplate = footer,
                       DisplayHeaderFooter = true,
                       MarginTop = "1cm",
                       MarginBottom = "1cm"
                   });

 var htmlContent = await JsReportMVCService.RenderViewToStringAsync(HttpContext, RouteData, "GerarPdf", dataTest);
                (var contentType, var generatedFile) = await GeneratePDFAsync(htmlContent);
                using (var fileStream = new FileStream("tempJsReport.pdf", FileMode.Create))
                {
                    await generatedFile.CopyToAsync(fileStream);
                }
        public async Task<(string ContentType, MemoryStream GeneratedFileStream)> GeneratePDFAsync(string htmlContent)
        {
            IJsReportFeature feature = new JsReportFeature(HttpContext);
            feature.Recipe(Recipe.ChromePdf);
            if (!feature.Enabled) return (null, null);
            feature.RenderRequest.Template.Content = htmlContent;

            // var htmlContent = await JsReportMVCService.RenderViewToStringAsync(HttpCSexontext, RouteData, "GerarPdf", retorno);
            var report = await JsReportMVCService.RenderAsync(feature.RenderRequest);
            var contentType = report.Meta.ContentType;
            MemoryStream ms = new MemoryStream();
            report.Content.CopyTo(ms);
            return (contentType, ms);
        }

The Problem, it generates a blank PDF, 0kb

The example is the same as what was published on github, but there is something that doesn't work htmlContent contains the html correctly.

pofider commented 4 years ago

There is a problem with your streams handling. You copy jsreport report stream to the memory stream. But afterward is the stream position at the end, so when you copy to the file, there are 0 bytes to copy. You need to seek the memory stream to the beginning with

report.Content.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);