Blazor中的Razor视图引擎(在运行时将blazor组件转换为html字符串)

时间:2019-02-08 14:50:39

标签: c# blazor blazor-server-side

我正在尝试在服务器端Blazor中生成pdf。我将DinkToPdf用作将HTML字符串转换为pdf的外部库。但是我无法将blazor组件转换为HTML字符串。

有一种方法可以使用Razor ViewEngine将Razor模板呈现为字符串。通过此网络http://fizzylogic.nl/2017/08/03/how-to-generate-pdf-documents-in-asp-net-core/

[HttpGet]
public async Task<IActionResult> CreatePDF()
{
    var globalSettings = new GlobalSettings
    {
        ColorMode = ColorMode.Color,
        Orientation = Orientation.Portrait,
        PaperSize = PaperKind.A4,
        Margins = new MarginSettings { Top = 10 },
        DocumentTitle = "PDF Report",
    };

    var objectSettings = new ObjectSettings
    {
        PagesCount = true,
        HtmlContent = "<h>Hello World</h>",
        WebSettings = { DefaultEncoding = "utf-8"},
        HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
        FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
    };

    var pdf = new HtmlToPdfDocument()
    {
        GlobalSettings = globalSettings,
        Objects = { objectSettings }
    };

    var file = _converter.Convert(pdf);
    return File(file,"application/pdf");
}

我需要将ObjectSettings.HtmlContent修改为blazor组件html字符串。

3 个答案:

答案 0 :(得分:1)

您是否要转换用户可以看到的内容?如果是这样,您可以在要渲染的组件中添加@ref='ContentToRender',然后Blazor将在渲染组件后分配该引用:

@inject IJSRuntime JSRuntime

<div @ref=ContentToRender>
  ... Your content here...
</div>

@code {
  ElementReference ContentToRender;

  protected async override Task OnAfterRenderAsync(bool firstRender) 
  {
    if (firstRender) 
    {
      string html = await JSRuntime.InvokeAsync<string>("BlazorUniversity.getInnerHTML", ContentToRender);
    }
  };
}

JS在哪里看起来像这样

var BlazorUniversity = BlazorUniversity || {};
BlazorUniversity.getInnerHTML = function(element) {
  return element.innerHTML;
};

别忘了在主index.html或_Host.cshtml页面中包含JS。

有关更多信息,请参见Blazor大学的Passing HTML Element References

请注意,至少在第一个渲染事件(firstRender == true)之后,您才能访问内容。

答案 1 :(得分:0)

这对我有用:

......         HtmlContent = TemplateGenerator.GetHTMLString(), ......

    public static string GetHTMLString()
    {
        IRaumNodeProvider RaumNodeProvider = new 
              RaumNodeProvider(Globals.Connectionstring);

        var reservierungen = RaumNodeProvider.GetReservierungen();

        var sb = new StringBuilder();
        sb.Append(@"
                    <html>
                        <head>
                        </head>
                        <body>
                            <div class='header'><h1>Reservierungsliste</h1></div>
                            <table align='center'>
                                <tr>
                                    <th>Id      </th>
                                    <th>Raum    </th>
                                    <th>Datum   </th>
                                    <th>Zeit    </th>
                                    <th>Beleger </th>
                                    <th>Belegung</th>
                                    <th>EmailMsg</th>
                                </tr>");

        foreach (var res in reservierungen)
        {
            sb.AppendFormat(@"<tr>
                                <td>{0}</td>
                                <td>{1}</td>
                                <td>{2}</td>
                                <td>{3}</td>
                                <td>{4}</td>
                                <td>{5}</td>
                                <td>{6}</td>
                              </tr>", 
                                res.Res_Id              
                              , res.RaumName                                  
                              , res.BelegungsDatumTxt   
                              , res.Zeit                
                              , res.Belegung_durch      
                              , res.Belegung            
                              , res.EmailMsg
                              );
        }

        sb.Append(@"
                            </table>
                        </body>
                    </html>");

        return sb.ToString();
    }

答案 2 :(得分:0)

我不得不深入研究一些源代码,这就是我发现适用于静态内容 (RenderMode.Static) 的内容(我还没有使用脚本标签或布局层次结构或嵌套组件对此进行测试)。< /p>

根据您尝试执行此操作的位置(即在请求中还是在后台任务中),您需要提供当前的 HttpContext 或创建自己的。

public static async Task<string> RenderAsync<TComponent>(IHtmlHelper helper, HttpContext httpContext, object parameters)
{
  if (helper is IViewContextAware viewContextAware)
  {
    viewContextAware.Contextualize(new ViewContext()
    {
      HttpContext = httpContext
    }
  }

  var content = await helper.RenderComponentAsync<TComponent>(RenderMode.Static, parameters);
  var writer = new StringWriter();
  content.WriteTo(writer, HtmlEncoder.Default);
  return writer.ToString();
}

public static HttpContext CreateDefaultContext(IServiceProvider serviceProvider)
{
  return new DefaultHttpContext
  {
    RequestServices = serviceProvider,
    Request =
    {
      Scheme = "http",
      Host = new HostString("localhost"),
      PathBase = "/base",
      Path = "/path",
      QueryString = QueryString.FromUriComponent("?query=value")
    }
  }
}

CreateDefaultContext 松散地基于 this sample found in Microsoft's tests

Sample.razor

<h3>@Data.Title</h3>

Hello, @Data.FirstName @Data.LastName!

@code {

  [Parameter]
  public Test Data { get; set; }

  public class Test
  {
    public string Title { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
  }

}

演示:

var helper = ServiceProvider.GetService<IHtmlHelper>();
var context = CreateDefaultContext(ServiceProvider);
var html = await RenderAsync<Sample>(helper, context, new
{
  Data = new Sample.Test()
  {
    Title = "Stack Overflow Test",
    FirstName = "user",
    LastName = "489566"
  }
});

html 值:

<h3>Stack Overflow Test</h3>

Hello, user 489566!