在 azure 中作为应用服务发布后,在使用 DinkToPDF 进行 PDF 转换时无法加载外部库“libwkhtmltox.dll”

swa*_*eph 6 azure .net-core dinktopdf

我正在使用 DinkToPDF 库将 html 字符串转换为等效的 PDF。要使用这个库,我们必须导入提供的本地库 libwkhtmltox.dll。当我在本地运行我的 .net 核心项目时,这工作正常,但是当我尝试在 Azure 中将我的 Web 项目发布为应用服务时,我收到以下错误,

未处理的异常:System.DllNotFoundException:无法加载共享库“/home/site/wwwroot/libwkhtmltox.dll”或其依赖项之一。为了帮助诊断加载问题,请考虑设置 LD_DEBUG 环境变量: /home/site/wwwroot/libwkhtmltox.dll: cannot open shared object file: No such file or directory

我在 startup.cs 文件中提到了库的用法,如下所示。

    internal class CustomAssemblyLoadContext : AssemblyLoadContext
    {
        public IntPtr LoadUnmanagedLibrary(string absolutePath)
        {
            return LoadUnmanagedDll(absolutePath);
        }
        protected override IntPtr LoadUnmanagedDll(String unmanagedDllName)
        {
            return LoadUnmanagedDllFromPath(unmanagedDllName);
        }

        protected override Assembly Load(AssemblyName assemblyName)
        {
            throw new NotImplementedException();
        }
    }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
            var context = new CustomAssemblyLoadContext();
            context.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), "libwkhtmltox.dll"));
         .
         .
         .
        }
Run Code Online (Sandbox Code Playgroud)

请帮我找出此错误的解决方案。

小智 1

您需要设置库的绝对路径,对于Windows,没有必要使用“.dll”,在我的情况下,它被放置在[project_root]/wkhtmltox/v0.12.4/[x_64|x_86]

var architectureFolder = (IntPtr.Size == 8) ? "x_64" : "x_86";
var wkHtmlToPdfFileName = "libwkhtmltox";
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    wkHtmlToPdfFileName += ".so";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
    wkHtmlToPdfFileName += ".dylib";
}

var wkHtmlToPdfPath = Path.Combine(
    new string[] {
        _hostingEnvironment.ContentRootPath,
        "wkhtmltox",
        "v0.12.4",
        architectureFolder,
        wkHtmlToPdfFileName
    });

CustomAssemblyLoadContext context = new CustomAssemblyLoadContext();
context.LoadUnmanagedLibrary(wkHtmlToPdfPath);
services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
Run Code Online (Sandbox Code Playgroud)