Blazor WASM PDF Generation with iTextSharp

674 Views Asked by At

I want to generate a PDF Document in Blazor WASM. I found examples with iTexSharp, so I did a small example.

Now I have two problems:

  1. I have trouble with the image path to add an image in the pdf:

     `Image img = Image.GetInstance("images/test.png");
    

    How need I set the image reference to my "wwwroot/images" folder?

  2. I get some error when I want to close my document with the command "document.Close()"

The error is:

System.Security.Cryptography.Algorithms is not supported on this 
platform.
System.PlatformNotSupportedException: System.Security.Cryptography.Algorithms is not supported on this platform.
   at System.Security.Cryptography.MD5.Create()
   at iTextSharp.text.pdf.PdfEncryption.CreateDocumentId()
   at iTextSharp.text.pdf.PdfWriter.Close()
   at iTextSharp.text.pdf.PdfDocument.Close()
   at iTextSharp.text.Document.Close()

Here is the whole code:

 _document = new Document(PageSize.A4, 10f, 10f, 20f, 30f);
        _pdfPTable.WidthPercentage = 50;
        _pdfPTable.HorizontalAlignment = Element.ALIGN_LEFT;
        _fontStyle = FontFactory.GetFont("Tahoma", 8f, 1);
        PdfWriter.GetInstance(_document, _memoryStream);
        _document.Open();

        float[] sizes = new float[_maxColumn];
        for (int i = 0; i < _maxColumn; i++)
        {
            if (i == 0) sizes[i] = 50;
            else sizes[i] = 100;
        }

        _pdfPTable.SetWidths(sizes);

        this.ReportHeader();
        this.ReporBody();

        _pdfPTable.HeaderRows = 2;
        _document.Add(_pdfPTable);
        _document.Close();

        return _memoryStream.ToArray();
1

There are 1 best solutions below

0
On

I have the same problem as you. What I found out is that because of WebAssembly sandbox constraint it will not be able to run itextsharp on the client side. That is why you are getting an error at the .close()

Read more at: https://learn.microsoft.com/en-us/dotnet/core/compatibility/cryptography/5.0/cryptography-apis-not-supported-on-blazor-webassembly

As for the problem with the image, if you have at the server side it will be able to be used. Otherwise you would need to make it an embedded resource and them stream it in.