5

I want to print a rendered modal that opens up with some vehicle information, The button is present on the modal and on click should convert the modal HTML to PDF.

Please advise if there is a C# function or so that I can use, which will extract the current HTML I want to convert to PDF, or steer me in the right direction. I have only been doing C# for about 2 months so lacking experience and expertise.

Edit: Also trying to get the code to use CSS when dumping the PDF.

I have added the following code.

References, etc. added.

@using BidWheels.Configuration;
@using BidWheels.Shared.Controls;
@using BidWheels.Data;
@using BidWheels.CustomProviders;
@using BidWheels.Services;
@using System.Timers;
@using Syncfusion.Pdf;
@using Syncfusion.HtmlConverter;
@using System.Linq;
@using System.Web;
@using Microsoft.AspNetCore.Http;

@inject AppState AppState;
@inject UsersDAL UsersDAL;
@inject MainDAL MainDAL;
@inject NotificationService NotificationService;
@inject GeneralConfiguration GeneralConfiguration;
@inject GlobalVar GlobalVar;
@inject GlobalVarShared GlobalVarShared;
@inject Microsoft.JSInterop.IJSRuntime JS
@inject IHttpContextAccessor httpContextAccessor

Button to proc the function to generate the PDF

        </div>
        <button class="btn btn-outline-success" @onclick="@CreatePDF">Generate PDF</button>
    </div>

This is the function invoked by the button.

@functions {

    void CreatePDF() 
    {

>         //Initialize HTML to PDF converter
>         //HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit);
>         //WebKitConverterSettings settings = new WebKitConverterSettings();
>         //Set WebKit path
>         //settings.WebKitPath = Server.MapPath("~/QtBinaries");
>         //Assign WebKit settings to HTML converter
>         //htmlConverter.ConverterSettings = settings;
>         //Get the current URL
>         //string url = HttpContext;
>         //Convert URL to PDF
>         //PdfDocument document = htmlConverter.Convert(url);
>         //Save the document
>         //document.Save("Sample.pdf", HttpContext.Current.Response, HttpReadType.Save);

Code updated to below
        HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
        WebKitConverterSettings webKitSettings = new WebKitConverterSettings();
        webKitSettings.WebKitPath = Directory.GetCurrentDirectory() + "\\wwwroot" + @"\QtBinariesWindows\";
        webKitSettings.MediaType = MediaType.Print;
        webKitSettings.Orientation = PdfPageOrientation.Portrait;
        htmlConverter.ConverterSettings = webKitSettings;
        Convert HTML to PDF.
        string baseUrl = @"" + Directory.GetCurrentDirectory() + "/wwwroot/css/";
        string HTMLBody = await JS.InvokeAsync<string>("getHTMLtoRender", PDFBody);
        PdfDocument pdfDocument = htmlConverter.Convert(HTMLBody, baseUrl);
        MemoryStream memoryStream = new MemoryStream();
        Save and close the document instance.
        pdfDocument.Save(memoryStream);
        JS.SaveAs("Sample.pdf", memoryStream.ToArray());

    }

}

The following errors are being generated.

Error messages generated by the code for the above:

Error messages generated by the code for the above

New errors generated and lib:

New errors generated and lib

karel
  • 5,489
  • 46
  • 45
  • 50
RastaFarier
  • 49
  • 1
  • 1
  • 4
  • Accessing the `HttpContext` in blazor is not a viable solution. If you need to switch your application to a WASM application it's not going to work an the main goal of Blazor is to run in the browser. Use a web api instead. If you still want to access the current `HttpContext`, try this solution https://stackoverflow.com/questions/53817373/how-do-i-access-httpcontext-in-server-side-blazor – agua from mars Mar 05 '20 at 15:31
  • I know this is an old question but I noticed a new blog post - 11 April 2023 - discussing exactly this: https://www.c-sharpcorner.com/article/how-to-create-pdf-using-itextsharp-in-blazor/. I haven't tried it so YMMV! – phuzi Apr 12 '23 at 08:44

4 Answers4

1

I always found programmatic PDF handling very difficult. If you really need a programmatic way take a look at this: Convert HTML to PDF in .NET. Otherwise I'd advise you to use the browsers print feature with a print to pdf tool, of wich at least one was usually already installed on every system i saw.

Patrick Beynio
  • 788
  • 1
  • 6
  • 13
1

1st render razor component to html string as the following

var host = new TestHost();
var component = host.AddComponent<YourComponent>();
var html = component.GetMarkup();

then pass this string to IronPdf library to generate the pdf for you

using IronPdf;
var Renderer = new IronPdf.ChromePdfRenderer();
var PDF = Renderer.RenderHtmlAsPdf(html);

References

  1. stackoverflow link How to render a Blazor component into an HTML string
  2. IronPdf IronPdf website
0

I've found a way to generate the PDF on the server and call it from your Blazor client side code. On the server you can avoid having to run a local PDF engine by using a HTTP service like https://rotativa.io (I'm the author of the service). I wrote a blog post about it and pushed a sample project on Github:

https://rotativa.io/site/blog/instructions/2023/03/15/create-pdf-in-blazor.html

https://github.com/RotativaHQ/RotativaIoBlazorSample

Giorgio Bozio
  • 2,982
  • 3
  • 20
  • 20
-1

Once you created the pdf as explained here you can use Append.Blazor.Printing to have a native print dialog. You can see the blogpost here.

example

Verbe
  • 634
  • 7
  • 13