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

.NET Maui如何实现文档(如PDF)打印?

.NET Maui 文档(PDF)打印解决方案

可以实现,以下是两种无额外成本或低成本的可行方案:


方案一:调用平台原生API实现(完全免费,无依赖)

.NET Maui本身没有内置打印API,但可以通过**依赖服务(Dependency Service)**调用各平台原生打印能力,直接处理PDF文件。

步骤1:定义共享服务接口

在共享项目中创建打印服务的统一接口:

public interface IPrintService
{
    Task PrintPdfAsync(string filePath);
}

步骤2:各平台实现服务

Android 平台

利用Android系统的PrintManager处理PDF文件流:

[assembly: Dependency(typeof(AndroidPrintService))]
namespace YourApp.Platforms.Android
{
    public class AndroidPrintService : IPrintService
    {
        public async Task PrintPdfAsync(string filePath)
        {
            var printManager = (PrintManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.PrintService);
            var printAdapter = new PdfPrintAdapter(filePath);
            printManager.Print("PDF 文档打印", printAdapter, null);
            await Task.CompletedTask;
        }

        private class PdfPrintAdapter : PrintDocumentAdapter
        {
            private readonly string _filePath;

            public PdfPrintAdapter(string filePath) => _filePath = filePath;

            public override void OnLayout(PrintAttributes oldAttrs, PrintAttributes newAttrs, CancellationSignal cancelSignal, LayoutResultCallback callback, Bundle extras)
            {
                if (cancelSignal.IsCanceled)
                {
                    callback.OnLayoutCancelled();
                    return;
                }

                var docInfo = new PrintDocumentInfo.Builder("PrintedDocument.pdf")
                    .SetContentType(PrintContentType.Document)
                    .SetPageCount(PrintDocumentInfo.PageCountUnknown)
                    .Build();

                callback.OnLayoutFinished(docInfo, true);
            }

            public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancelSignal, WriteResultCallback callback)
            {
                try
                {
                    using var inputStream = new FileStream(_filePath, FileMode.Open);
                    using var outputStream = new FileStream(destination.FileDescriptor, FileAccess.Write);
                    inputStream.CopyTo(outputStream);
                    callback.OnWriteFinished(pages);
                }
                catch (Exception ex)
                {
                    callback.OnWriteFailed(ex.Message);
                }
            }
        }
    }
}

iOS 平台

使用iOS的UIPrintInteractionController加载PDF文件:

[assembly: Dependency(typeof(IosPrintService))]
namespace YourApp.Platforms.iOS
{
    public class IosPrintService : IPrintService
    {
        public async Task PrintPdfAsync(string filePath)
        {
            var printController = UIPrintInteractionController.SharedPrintController;
            if (!printController.CanPrint) return;

            var pdfUrl = NSUrl.FromFilename(filePath);
            printController.PrintFormatter = new UIPrintFormatter(pdfUrl);

            printController.Present(true, (_, completed, error) =>
            {
                if (error != null)
                {
                    // 可在此添加错误提示逻辑
                }
            });

            await Task.CompletedTask;
        }
    }
}

Windows 平台

调用Windows打印管理器加载本地PDF:

[assembly: Dependency(typeof(WindowsPrintService))]
namespace YourApp.Platforms.Windows
{
    public class WindowsPrintService : IPrintService
    {
        public async Task PrintPdfAsync(string filePath)
        {
            var printManager = PrintManager.GetForCurrentView();
            printManager.PrintTaskRequested += (sender, args) =>
            {
                var deferral = args.Request.GetDeferral();
                try
                {
                    args.Request.CreatePrintTask("PDF 文档打印", sourceReq =>
                    {
                        var pdfDoc = PdfDocument.LoadFromFileAsync(filePath).GetAwaiter().GetResult();
                        sourceReq.SetSource(pdfDoc);
                    }).Completed += (task, args) =>
                    {
                        if (args.Completion == PrintTaskCompletion.Failed)
                        {
                            // 可在此添加错误提示逻辑
                        }
                    };
                }
                finally
                {
                    deferral.Complete();
                }
            };

            await PrintManager.ShowPrintUIAsync();
        }
    }
}

步骤3:在共享项目中调用

var printService = DependencyService.Get<IPrintService>();
await printService.PrintPdfAsync("你的PDF文件本地路径");

方案二:使用免费社区版NuGet包

如果不想写原生代码,可以使用Syncfusion.Maui.PdfViewer的社区版(非商业项目免费),它内置了一键打印功能:

var pdfViewer = new SfPdfViewer();
pdfViewer.LoadDocument("你的PDF文件路径");
await pdfViewer.PrintDocumentAsync();

注意:商用项目需购买授权,社区版有功能和使用限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:23:19