You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Function中用PDF Sharp转HTML到PDF报错:无法保存无页面PDF

问题:Azure Function中使用PDF Sharp生成PDF报错“Cannot save a PDF document with no pages.”

本地运行HTML转PDF代码正常,但部署到Azure Function后通过Postman调用时出现该错误,本地与云端传入的HTML内容完全一致,相关代码如下:

using PdfSharp.Pdf;
using PdfSharp;
using PdfSharp.Drawing;
using TheArtOfDev.HtmlRenderer.PdfSharp;

public byte[] HtmlToPDF(string html)
{
    try
    {
        byte[] pdfBytes;

        using (var ms = new MemoryStream())
        {
            System.Text.Encoding.RegisterProvider(
                System.Text.CodePagesEncodingProvider.Instance
            );
            
            // 报错行
            var pdf = PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
            pdf.Save(ms);
            pdfBytes = ms.ToArray();
        }

       return pdfBytes;

    }
    catch (Exception ex)
    {
        throw new Exception(ex);
    }            
}

排查与解决方案

  • 字体缺失导致渲染失败:Azure Function默认运行环境缺少部分系统字体,HTML渲染时无法解析字体,导致没有生成任何页面。
    解决办法:

    1. 在HTML中明确指定Azure环境支持的字体(如Arial、Times New Roman);
    2. 将所需字体文件打包到Azure Function部署包中,在代码中注册字体:
      // 在生成PDF前注册字体
      var fontPath = Path.Combine(Environment.GetEnvironmentVariable("HOME"), "site", "wwwroot", "fonts", "Arial.ttf");
      PrivateFontCollection pfc = new PrivateFontCollection();
      pfc.AddFontFile(fontPath);
      
      // 配置生成选项指定字体
      var config = new PdfGenerateConfig();
      config.FontResolver = new DefaultFontResolver(pfc);
      var pdf = PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4, config);
      
  • 编码兼容性问题:虽然注册了CodePagesEncodingProvider,但Azure环境的编码支持可能存在差异,确保HTML内容为UTF-8编码:

    html = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(html));
    
  • 依赖版本不兼容:检查PdfSharp和TheArtOfDev.HtmlRenderer.PdfSharp的版本,确保与Azure Function使用的.NET版本兼容,统一项目的目标框架版本(如本地和云端都用.NET 6)。

  • HTML内容渲染兼容性:部分复杂CSS布局或特殊标签在Azure环境的渲染引擎中不支持,尝试简化HTML内容测试,逐步定位导致渲染失败的部分。

内容的提问来源于stack exchange,提问作者Dicpherrr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 01:58:20