2

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;
      }
   }
}
4

2 回答 2

0

我看不到你是如何得到ConverterToPdf的,但你可以试试这个:如果你var converter = new SynchronizedConverter(new PdfTools());´, remove it, and just inject在你的服务中使用 IConverter` 初始化转换器。

我试过了,这种方法是有效的,毕竟我们已经注册了转换器,我们不需要使用 new关键字创建实例。

于 2019-12-11T13:18:32.253 回答
0

它是您在 Startup.cs 上创建的单例,因此您首先需要做的是使用依赖注入填充根对象。

private readonly IConverter _converter;

public YourControllerService(IConverter converter)
{            
    _converter = converter            
}

public void CreatePdf() {
    byte[] bytes = _converter.Convert(doc);
}

其次,确保使用网络安全字体来加快渲染速度。在 html 中使用来自外部 url 的字体会减慢这个过程。例如,假设这是您的 html 模板,并且您有 5 个页面:

<html>
<head>
    <style>
        @import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,700');
        body {
            font-family: 'Source Sans Pro', sans-serif;
        }
    <style>
<head>
</html>

如果你改变它:

<html>
<head>
    <style>         
        body {
            font-family: 'Verdana'; 
        }
    <style>
<head>
</html>

你会看到速度差异。此外,根据我的经验,降低 DPI 也会影响渲染速度。

var doc = new HtmlToPdfDocument()
{
    GlobalSettings = {
        ColorMode = ColorMode.Color,
        Orientation = Orientation.Landscape,
        PaperSize = PaperKind.A4,
        DPI = 320,
        Out = path
    },
    Objects = {
        new ObjectSettings() {                               
            PagesCount = true,
            HtmlContent = html,
            WebSettings = { DefaultEncoding = "UTF-8", LoadImages = true },
            FooterSettings = { FontSize = 8, Right = "Page [page] of [toPage]", Line = false, Spacing = 2.812 }
        }
    }
};

byte[] bytes = _converter.Convert(doc);

希望有帮助。

于 2020-01-31T12:52:28.667 回答