0

I am converting the string html data to pdf with the code block below, it completes the pdf conversion process perfectly in the first run, but it deletes the html tags in subsequent conversions.

            using (var converter = new SynchronizedConverter( new PdfTools()))
                {
                    var doc = new HtmlToPdfDocument()
                    {
                        GlobalSettings = {
                            ColorMode = ColorMode.Color,
                            Orientation = Orientation.Landscape,
                            PaperSize = PaperKind.A4,
                        },
                        Objects = {
                        new ObjectSettings() {
                            PagesCount = true,
                            HtmlContent = newHtmlString,
                            WebSettings = { DefaultEncoding = "utf-8" },
                            HeaderSettings = { FontSize = 9, Right = "Sayfa [page] / [toPage]", Line = true, Spacing = 2.812 }
                        }
                    }
                    };

                    var returnByte = converter.Convert(doc); 
                }; 

I tried to dispose of the converter, but this time I encountered a memory corruption error.

M.Merth
  • 13
  • 5
  • According to the [documentation](https://github.com/HakanL/WkHtmlToPdf-DotNet) SynchronizedConverter should be a singleton. You create a new instance every time. – Palle Due Jun 21 '23 at 08:28

1 Answers1

0

Create the SynchronizedConverter once and use it althrough the code. You cannot have multiple instances of it.

// Initialization
private SynchronizedConverter myConverter = new SynchronizedConverter(new PdfTools());

...
var doc = new HtmlToPdfDocument()
{
    GlobalSettings = {
        ColorMode = ColorMode.Color,
        Orientation = Orientation.Landscape,
        PaperSize = PaperKind.A4,
    },
    Objects = {
        new ObjectSettings() {
        PagesCount = true,
        HtmlContent = newHtmlString,
        WebSettings = { DefaultEncoding = "utf-8" },
        HeaderSettings = { FontSize = 9, Right = "Sayfa [page] / [toPage]", Line = true, Spacing = 2.812 }
     }
};

var returnByte = myConverter.Convert(doc); 

You can also use dependency injection and inject it as a singleton as suggested in the documentation.

Palle Due
  • 5,929
  • 4
  • 17
  • 32
  • Thanks for your advice. Actually, the first version of the code was as you stated, when you run it in this way, the pdf is created for the first time, but it gives a timeout error in the next times. This is an angular project, we convert the html string from the frontend to pdf with c#. – M.Merth Jun 21 '23 at 09:48
  • When I checked again using "inject it as a singleton" solved my problem thank you. – M.Merth Jun 21 '23 at 11:11
  • You're welcome. Manually making it a singleton can easily lead to threading issues in your setup. Dependency injection would solve that. – Palle Due Jun 21 '23 at 12:05