在macOS上的IronPrint与.NET 8 (Apple Silicon)

This article was translated from English: Does it need improvement?
Translated
View the article in English

在Apple Silicon macOS上的.NET 8 控制台应用程序中运行IronPrint可能在构建时因缺少本机库而失败,Printer.GetPrinterNamesAsync()会在运行时抛出异常。

System.PlatformNotSupportedException: System.Drawing.Common is not supported on this platform.

macOS不提供net8.0目标永远不会启用macOS特定的平台API。两个缺口都需要填补。

解决方案

1. 安装本地GDI+库

通过Homebrew安装libgdiplus,以便在macOS上可以获得Windows默认提供的GDI+支持:

brew install mono-libgdiplus
brew install mono-libgdiplus
SHELL

没有这个库,System.Drawing就没有可调用的本机后端。

2. 以macOS框架为目标

将您的net8.0

<TargetFramework>net8.0-macos</TargetFramework>
<TargetFramework>net8.0-macos</TargetFramework>
XML

这表明.NET使用macOS平台API而不是跨平台存根。

警告net8.0-macos不是默认控制台应用程序模板的一部分。 安装macOS工作负载或从macOS应用程序模板开始以获取预配置支持。

一个完整的项目文件如下所示:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0-macos</TargetFramework>
    <Nullable>enable</Nullable>
    <UseSystemDrawing>true</UseSystemDrawing>
  </PropertyGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0-macos</TargetFramework>
    <Nullable>enable</Nullable>
    <UseSystemDrawing>true</UseSystemDrawing>
  </PropertyGroup>
</Project>
XML

3. 使用兼容的打印API

在macOS上,调用ShowPrintDialogAsync()进行打印操作,而不是依赖仅限Windows的打印路径。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 44,051 | 版本: 2026.7 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronPrint
运行示例 观看您的文档打到打印机上。