为 Wpf DocumentViewer PrintDialog 设置页面方向

18

使用 Wpf 的 DocumentViewer 控件时,我无法弄清如何在用户单击打印按钮时设置 DocumentViewer 显示的 PrintDialog 的 PageOrientation。有什么方法可以进行挂钩吗?

2个回答

16

Mike的回答可行。我选择的实现方式是创建自己的文档查看器,该查看器派生自DocumentViewer。此外,将Document属性强制转换为FixedDocument对我没有起作用-强制转换为FixedDocumentSequence有用。

GetDesiredPageOrientation可以根据您的需要进行设置。在我的情况下,我检查第一页的尺寸,因为我生成的文档具有统一的大小和方向,并且序列中仅有一个文档。

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using System.Windows.Xps;
using System.Printing;
using System.Windows.Documents;

public class MyDocumentViewer : DocumentViewer
{
    protected override void OnPrintCommand()
    {
        // get a print dialog, defaulted to default printer and default printer's preferences.
        PrintDialog printDialog = new PrintDialog();
        printDialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();
        printDialog.PrintTicket = printDialog.PrintQueue.DefaultPrintTicket;

        // get a reference to the FixedDocumentSequence for the viewer.
        FixedDocumentSequence docSeq = this.Document as FixedDocumentSequence;

        // set the default page orientation based on the desired output.
        printDialog.PrintTicket.PageOrientation = GetDesiredPageOrientation(docSeq);

        if (printDialog.ShowDialog() == true)
        {
            // set the print ticket for the document sequence and write it to the printer.
            docSeq.PrintTicket = printDialog.PrintTicket;

            XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(printDialog.PrintQueue);
            writer.WriteAsync(docSeq, printDialog.PrintTicket);
        }
    }
}

我已经覆盖了默认的DocumentViewer,因为它包含了非本地化友好的文本,所以这是一个很好的解决方案。谢谢! - JoeB
应该是 printDialog.PrintTicket = printDialog.PrintQueue.DefaultPrintTicket; 吗?否则无法编译。 - Anders Lindén
也很希望看到您实现GetDesiredPageOrientation的方式! - Anders Lindén
已注意并修复。谢谢。另外:https://gist.github.com/mcw0933/5543526 只需调用GetPageOrientationOfFirstPageOfFixedDocSeq函数即可。 - mcw

10

我用的解决方法是通过在我的DocumentViewer打印对话框上隐藏打印按钮来设置方向,方法是从模板中省略该按钮。然后我提供了自己的打印按钮,并将其绑定到以下代码:

public bool Print()
    {
        PrintDialog dialog = new PrintDialog();
        dialog.PrintQueue = LocalPrintServer.GetDefaultPrintQueue();
        dialog.PrintTicket = dialog.PrintQueue.DefaultPrintTicket;
        dialog.PrintTicket.PageOrientation = PageOrientation.Landscape;

        if (dialog.ShowDialog() == true)
        {
            XpsDocumentWriter writer = PrintQueue.CreateXpsDocumentWriter(dialog.PrintQueue);
            writer.WriteAsync(_DocumentViewer.Document as FixedDocument, dialog.PrintTicket);
            return true;
        }

        return false;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接