Search code examples
c#.net.net-corepdf-generationwkhtmltopdf

WkHtmlToPdfDotNet not working properly after first run


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.


Solution

  • 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.