Processing of Converting the html to PDF takes a long time by using DinkToPdf
library, when this line of code runs: ConverterToPdf.Convert(pdf)
How can I solve this problem?
public byte[] ConvertReportToPDFAsync<TViewModel>() where TViewModel : new()
{
var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 10 },
DocumentTitle = documentTitle,
};
var objectSettings = new ObjectSettings
{
PagesCount = true,
HtmlContent =@"<html><body><div>Hello</div></body></html>",
WebSettings = { DefaultEncoding = "utf -8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "PruefReportDataTableFormat.css") },
HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
};
var pdf = new HtmlToPdfDocument()
{
GlobalSettings = globalSettings,
Objects = { objectSettings }
};
byte[] file = ConverterToPdf.Convert(pdf); // TOO LONG PROCESS !!!!
return file;
}
Startup class:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMemoryCache(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();
services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools())); // DinkToPdf
}
}
Updated:
After tracing, I figured out the problem is in WkHtmlToXBindings.wkhtmltopdf_convert
method in namespace DinkToPdf
namespace DinkToPdf
{
public sealed class PdfTools : ITools, IDisposable
{
// some codes
public bool DoConversion(IntPtr converter)
{
return WkHtmlToXBindings.wkhtmltopdf_convert(converter); // ACTUALLY TOO LONG PROCESS OCCURS HERE !!!!
}
}
}
Update 2:
After deep tracing, I figured out that in this line of code, Monitor.Wait((object) task1);
, occurred long process!
(I cannot change this code, because this code is part of dinktopdf.dll
file.)
namespace DinkToPdf
{
public class SynchronizedConverter : BasicConverter
{
public TResult Invoke<TResult>(Func<TResult> @delegate)
{
this.StartThread();
Task<TResult> task1 = new Task<TResult>(@delegate);
Task<TResult> task2 = task1;
bool lockTaken = false;
try
{
Monitor.Enter((object) task2, ref lockTaken);
this.conversions.Add((Task) task1);
Monitor.Wait((object) task1); //Bottleneck!! LONG PROCESS!!
}
finally
{
if (lockTaken)
Monitor.Exit((object) task2);
}
if (task1.Exception != null)
throw task1.Exception;
return task1.Result;
}
}
}