在Blazor中添加SelectPDF的文件流服务器端

问题描述

我正在尝试将HTML代码导出为PDF。我需要保存到客户端浏览器而不是服务器。我在网上找到的所有内容都是保存到root,然后下载到浏览器。如果可能的话,我想避免该步骤。

void ExportPDF()
    {
        SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
        SelectPdf.PdfDocument doc = converter.ConvertUrl("https://selectpdf.com");
        doc.Save("test.pdf");
        doc.Close();
    }

解决方法

您可以将documentation保存到Stream。因此您的代码将是

  SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
  SelectPdf.PdfDocument doc = converter.ConvertUrl("https://selectpdf.com");
  using (var ms = new System.IO.MemoryStream())
  {
    doc.Save(ms);
    doc.Close();
    // todo- create response using the data in `ms`
  }

由于这是Blazor的问题,我会问这个方法是否在Component内部?如果是这样,则无法通过组件内部的浏览器下载文件。您需要在控制器操作中编写此方法,然后返回FileResult。然后,在Blazor组件中,您需要导航到控制器,这将导致浏览器下载文件。

有关更多详细信息,请参见Is there a way to get a file stream to download to the browser in Blazor?