将文件名传递给 PrintDialog.PrintDocument

问题描述 投票:0回答:1

我有一个流程文档,需要将其写入 PDF 文件。使用下面的代码会打开一个对话框,询问文件名,然后生成 pdf。

var flowDocument = documentTemplate.LoadContent() as FlowDocument;
flowDocument.PageWidth = printDialog.PrintableAreaWidth;
flowDocument.PageHeight = printDialog.PrintableAreaHeight;
var paginator = new HeaderFooterPaginator<HeaderModel, FooterModel>(0, flowDocument, GetHeader(), GetFooter());
printDialog.PrintDocument(paginator, "My Document");

但是,如果存在相同的 pdf 并且它已打开,则此代码会崩溃。 如何将文件名传递给 PrintDocument 函数?

编辑: 我知道捕获异常。现在,在引发异常之后,我希望文件名中包含日期时间。

c# .net wpf printing
1个回答
0
投票

@BionicCode 评论作为答案:

发生异常时要求用户提供另一个文件名。

while (true)
{
    try
    {
        printDialog.PrintDocument(paginator, "My Document");
        break;
    }
    catch (Exception)
    {
        var result = MessageBox.Show("The file is already opened. Close and retry or provide another filename.", "Error", MessageBoxButton.OKCancel, MessageBoxImage.Error);
        if (result == MessageBoxResult.Cancel) break;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.