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

ASP.NET Core 8中使用Pdfium打印PDF时加载System.Windows.Forms失败

问题根源

你遇到的错误是因为ASP.NET Core 8是跨平台的服务端框架,默认不包含System.Windows.Forms这类Windows桌面UI组件,而你使用的Pdfium相关包大概率依赖了WinForms的打印API来实现功能,服务端环境(尤其是非Windows服务器)无法加载该组件。

解决方案

方案1:前端处理打印(推荐)

将Base64 PDF字符串返回给前端,由浏览器负责触发打印,完全规避服务端依赖桌面组件的问题:

// 前端JS代码
function printPdf(base64Pdf) {
    const blob = b64toBlob(base64Pdf, 'application/pdf');
    const url = URL.createObjectURL(blob);
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = url;
    document.body.appendChild(iframe);
    iframe.onload = function() {
        iframe.contentWindow.print();
        setTimeout(() => {
            URL.revokeObjectURL(url);
            document.body.removeChild(iframe);
        }, 1000);
    };
}

function b64toBlob(b64Data, contentType) {
    const sliceSize = 512;
    const byteCharacters = atob(b64Data);
    const byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    return new Blob(byteArrays, {type: contentType});
}

方案2:Windows服务器下调用系统打印命令

如果必须在服务端处理,且服务器是Windows系统,可以将Base64转成临时PDF文件,调用系统默认PDF阅读器的打印功能:

// C#服务端代码
byte[] pdfBytes = Convert.FromBase64String(base64Pdf);
string tempPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.pdf");
File.WriteAllBytes(tempPath, pdfBytes);

// 调用系统打印命令
ProcessStartInfo psi = new ProcessStartInfo
{
    FileName = tempPath,
    Verb = "print",
    CreateNoWindow = true,
    UseShellExecute = true
};
using var printProcess = Process.Start(psi);
printProcess.WaitForExit();

// 打印完成后删除临时文件
File.Delete(tempPath);

注意:需确保服务器安装了默认PDF阅读器(如Edge、Acrobat),且应用池账户有打印权限。

方案3:启用WinForms兼容(不推荐生产环境)

若坚持使用Pdfium的WinForms依赖,需修改项目配置并部署在Windows服务器:

  1. 在项目的.csproj文件中添加以下配置:
<PropertyGroup>
  <TargetFramework>net8.0-windows</TargetFramework>
  <UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
  1. 服务器需安装.NET Desktop Runtime(ASP.NET Core Runtime默认不包含WinForms组件)。
    这种方式会让服务端依赖桌面组件,存在稳定性、权限隐患,仅适合测试场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 17:29:55