7

我正在尝试在服务器端 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 字符串。

4

3 回答 3

2

您是否尝试转换用户可以看到的内容?如果是这样,您可以添加@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 大学传递 HTML 元素引用

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

于 2019-11-29T13:12:32.580 回答
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();
    }
于 2019-02-11T07:46:43.153 回答
0

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

根据您尝试执行此操作的位置(即在请求与后台任务中),您将需要提供电流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大致基于Microsoft 测试中发现的这个样本

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!
于 2021-02-08T23:17:27.057 回答