DinkToPdf
当这行代码运行时,使用库将html转换为PDF的处理需要很长时间:ConverterToPdf.Convert(pdf)
我怎么解决这个问题?
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;
}
启动类:
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
}
}
更新:
跟踪后,我发现问题出在 WkHtmlToXBindings.wkhtmltopdf_convert
方法中 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 !!!!
}
}
}
更新 2:
经过深度追踪,发现这行代码 Monitor.Wait((object) task1);
,,,发生了漫长的过程!
(我无法更改此代码,因为此代码是dinktopdf.dll
文件的一部分。)
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;
}
}
}