blazorblazor-server-sideselectpdf

Adding file stream for SelectPDF in Blazor (Server-Side)


I am trying to export HTML code as PDF. I need to save to client browser instead of server. All I've been able to find online is to save to root then download to browser. I'd like to avoid that step if possible.

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

Solution

  • Looking at the documentation you can save to a Stream instead. So your code would be

      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`
      }
    

    As this is a Blazor question, I would ask if this method is inside a Component? If so there isn't a way to download a file on the browser inside a component. You need to write this method in a controller action and return a FileResult. In the Blazor component you then need to navigate to the controller, which will cause the browser to download the file.

    See Is there a way to get a file stream to download to the browser in Blazor? for more detail