You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

WPF C#中如何为FlowDocument指定Microsoft Print to PDF打印机

实现固定使用Microsoft Print to PDF打印FlowDocument

当然可以实现!你不用每次手动切换打印机,通过代码就能强制让FlowDocument的打印操作默认使用Microsoft Print to PDF,下面是两种靠谱的实现方式:

方法1:在打印逻辑中直接指定目标打印机

如果是通过WPF的PrintDialog来触发打印,你可以在显示对话框前,主动筛选并设置打印机为Microsoft Print to PDF。示例代码如下:

var printDialog = new PrintDialog();
// 查找Microsoft Print to PDF打印机
var pdfPrinter = printDialog.PrintQueueCollection.FirstOrDefault(pq => 
    pq.Name.Equals("Microsoft Print to PDF", StringComparison.OrdinalIgnoreCase));

if (pdfPrinter != null)
{
    printDialog.PrintQueue = pdfPrinter;
    // 可选:如果想直接打印不弹出对话框,去掉ShowDialog()调用,直接调用PrintDocument
    if (printDialog.ShowDialog() == true)
    {
        var flowDocument = YourFlowDocument; // 替换成你的FlowDocument实例
        printDialog.PrintDocument(((IDocumentPaginatorSource)flowDocument).DocumentPaginator, "打印文档");
    }
}
else
{
    MessageBox.Show("未找到Microsoft Print to PDF打印机,请先启用该功能。");
}

这段代码会先在可用打印机列表里定位到Microsoft Print to PDF,直接把它设为PrintDialog的默认选择;要是不需要用户确认,你甚至可以跳过ShowDialog()直接调用PrintDocument实现静默打印。

方法2:设置应用级别的默认打印队列

如果你希望整个应用里所有的打印操作都默认用这个打印机,还可以在应用启动时设置全局的打印队列:

using System.Printing;

// 在App.xaml.cs的OnStartup方法里添加
protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    var printServer = new LocalPrintServer();
    var pdfPrinter = printServer.GetPrintQueues().FirstOrDefault(pq => 
        pq.Name.Equals("Microsoft Print to PDF", StringComparison.OrdinalIgnoreCase));
    
    if (pdfPrinter != null)
    {
        printServer.DefaultPrintQueue = pdfPrinter;
    }
}

这样设置后,应用里所有使用默认打印队列的操作都会自动选用Microsoft Print to PDF,包括FlowDocument的打印。

注意事项

  • 确保系统已经启用了Microsoft Print to PDF功能:如果找不到这个打印机,你可以在设置 > 蓝牙和设备 > 打印机和扫描仪 > 添加设备里手动添加,或者在控制面板的「程序和功能」中启用Windows功能。
  • 打印机名称可能因系统语言不同略有差异,比如非英文系统里名称可能有本地化翻译,需要调整字符串匹配的内容。

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

火山引擎 最新活动