.Net中打印页面的页数

.Net中打印页面的页数,.net,printing,.net,Printing,我希望能够将第1页(共7页)这样的页码放在我从应用程序打印的页面上。因此,我实现了一个两遍打印例程。第一次传递打印到一个文件,完成后会自动取消。第一遍的总页数用于第二遍,我将数据发送到打印机 下面是生成两种打印文档的代码 public static PrintDocument CreatePrintDocument(PrinterConfiguration printerConfig) { PrintDocument document = new PrintDocume

我希望能够将第1页(共7页)这样的页码放在我从应用程序打印的页面上。因此,我实现了一个两遍打印例程。第一次传递打印到一个文件,完成后会自动取消。第一遍的总页数用于第二遍,我将数据发送到打印机

下面是生成两种打印文档的代码

 public static PrintDocument CreatePrintDocument(PrinterConfiguration printerConfig)
    {
        PrintDocument document = new PrintDocument();
        document.PrinterSettings.PrinterName = printerConfig.PrinterName;
        document.DefaultPageSettings.Landscape = printerConfig.IsLandscape;
        document.PrintController = new StandardPrintController(); 
        return document;
    }

    public static PrintDocument CreatePrintDocumentThatCancelsPrint(PrinterConfiguration printerConfig)
    {
        PrintDocument document = CreatePrintDocument(printerConfig);
        document.PrinterSettings.PrintToFile = true;
        document.PrinterSettings.PrintFileName = CreateTempFileName();
        document.EndPrint += (sender, e) => { e.Cancel = true; };
        return document;
    }
问题是PrintToFile并不总是有效。在一台Windows XP测试计算机上,我在执行第一次传递时得到一个Win32Exception无效句柄。所以在谷歌搜索了一段时间后,我发现不支持从代码中设置PrintDocument.PrintToFile

PrintToFile属性仅由PrintDialog使用,不能以编程方式设置。

那么,为什么不直接打印到打印机并在EndPrint事件中取消它呢?那么,如果打印到XPS Document Writer打印机,那么用户将获得第一次和第二次的“另存为”问题

所以问题是,;在打印到XPS Document Writer时,如何进行两遍打印而不看到“另存为”对话框两次

决议

正如JonB指出的,我需要查看PreviewPrintController,因为它是一个打印控制器,允许我与所选打印机进行静默交互

public static PrintDocument CreatePrintDocument(PrinterConfiguration printerConfig)
{
    PrintDocument document = new PrintDocument();
    document.PrinterSettings.PrinterName = printerConfig.PrinterName;
    document.DefaultPageSettings.Landscape = printerConfig.IsLandscape;
    document.PrintController = new StandardPrintController(); 
    return document;
}

public static PrintDocument CreatePrintDocumentThatCancelsPrint(PrinterConfiguration printerConfig)
{
    PrintDocument document = new PrintDocument();
    document.PrinterSettings.PrinterName = printerConfig.PrinterName;
    document.DefaultPageSettings.Landscape = printerConfig.IsLandscape;
    document.PrintController = new PreviewPrintController();        
    document.EndPrint += (sender, e) => { e.Cancel = true; };
    return document;
}

第一次尝试使用“打印预览”对话框,如果愿意,可以将其隐藏。我担心打印预览对话框会给我带来另一个问题,因为我们也在尝试从服务打印。请注意,我描述的问题发生在将应用程序作为普通控制台应用程序运行时。@JonB在考虑了您的评论一段时间后,我意识到我可以使用PreviewPrintController,而不必实际使用预览查看器控件。明天我将测试使用PreviewPrintController而不是StandardPrintController进行第一次打印。