在 Azure Web 应用程序上使用 wkhtmltopdf 包装器 nreco 自定义字体

custom fonts with wkhtmltopdf wrapper nreco on azure web app

我正在使用 .net 包装器 "NReco.PdfGenerator" 将 html 文件转换为 pdf for wkhtmltopdf on azure web app(运行 在标准计划中) 但不能在我的文档中包含自定义字体。 自定义字体不会被 PDF 生成器加载或只是被忽略。 我尝试了不同的格式来包含字体文件,例如 link 到 google 字体 css、从 google 字体导入、相对本地路径、绝对本地路径、加载字体使用 base64 编码字体通过本地主机和字体面文件:

@@font-face {
            font-family: 'testfont';
            src:  url(data:application/x-font-woff;charset=utf-8;base64,...) format('woff');
            font-weight: normal;
            font-style: normal;
        }

使用:

font-family: 'testfont';

@@ 因为我正在使用剃刀视图。将生成的 HTML 保存到文件时,在浏览器 (chrome) 中打开时看起来不错并且工作正常。

正在生成 PDF:

var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
return htmlToPdf.GeneratePdf(html);

我还从 font-family 语句中删除了备份字体。 我尝试了 wkhtmltopdf 的不同版本,但没有成功。 生成器可以很好地处理来自本地主机的图像。

当 运行 在我的 windows 机器上使用相同的 asp.net 应用程序时,字体工作正常。

NReco 文档说 "avoid usage of custom fonts"(在 azure web 应用程序环境中),这是否意味着没有机会获得它 运行?为什么不支持自定义字体?有什么解决方法吗?

感谢您的帮助。

这是已知问题:Azure Apps 托管环境限制了一些 GDI API,因此 wkhtmltopdf 无法加载(和呈现)自定义字体。默认情况下只能使用 Windows 上存在的标准字体(如 Arial、Times New Roman 等)。您可以就此主题联系 Azure 支持 - 他们可以提供有关 Azure Apps 沙盒限制的更多详细信息。

Why are custom fonts not supported? Is there any workaround?

根据 Azure official document,我们可以知道目前 Azure WebApp 不支持 NReco(使用 wkhtmltopdf)。以下是文档的片段。

PDF generation from HTML

There are multiple libraries used to convert HTML to PDF. Many Windows/.NET specific versions leverage IE APIs and therefore leverage User32/GDI32 extensively. These APIs are largely blocked in the sandbox (regardless of plan) and therefore these frameworks do not work in the sandbox.

There are some frameworks that do not leverage User32/GDI32 extensively (wkhtmltopdf, for example) and we are working on enabling these in Basic+ the same way we enabled SQL Reporting.

Unsupported frameworks

Here is a list of frameworks and scenarios that have been found to be not be usable due to one or more of the restrictions above. It's conceivable that some will be supported in the future as the sandbox evolves.

PDF generators failing due to restriction mentioned above:

  • Syncfusion
  • Siberix
  • NReco (uses wkhtmltopdf)
  • Spire.PDF

如果Nreco不是唯一的选择。请尝试使用以下方式:

The following PDF generators are supported:

  • SQL Reporting framework: requires the site to run in Basic or higher (not that this currently does not work Functions apps)

  • EVOPDF: See http://www.evopdf.com/azure-html-to-pdf-converter.aspx for vendor solution

  • Telerik reporting: requires the site to run in Basic or higher.

  • Rotativa / wkhtmltopdf: requires the site to run in Basic or higher.

要克服 azure web 应用沙箱限制(自定义字体呈现),您可以使用应用服务中的 Windows 容器来应用自定义字体: https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-windows-containers-custom-fonts