PrintDocument卡住(看似机器重启后)

时间:2015-10-16 17:13:18

标签: .net wpf printing printdocument

我已经打了很长时间了,而且现在比以前好多了。我在WPF应用程序中有一段C#代码,用于监视已知文件夹并在出现时打印该文件夹中的图像。文件夹结构如下:

  • 已知文件夹
    • 打印作业1文件夹
      • PNG文件1
      • PNG文件2
    • 打印作业2文件夹
      • PNG文件1
  • ......等等

这是一段代码:

namespace Something.InStoreExperience.SalesDeviceMonitor.Plugins
{
    public class PrintImagesPlugin : MonitorPlugin
    {
        private readonly object _lock = new object();

        protected override void DoWork(UpdateManager<DirectoryInfo> updateManager, ISalesDeviceMonitor salesDeviceMonitor)
        {
            if (!Enabled)
            {
                PrintLoggingSource.Log.Debug("PrintImagesPlugin disabled.  Quitting.");
                return;
            }

            //lock (_lock)
            //{
            try
            {
                    List<string> printFolders;
                    lock (_lock)
                    {
                        //get all of our finished folders (that aren't already being printed) and try to print the images inside them.
                        printFolders = Directory.GetDirectories(updateManager.SomethingKnownFolders.PrintImages.Path)
                                                .Where(d => !d.Contains("-InProgress") && !d.Contains("-Processing")).ToList();

                        if (!printFolders.Any())
                            return;

                        PrintLoggingSource.Log.Debug(string.Format("Found {0} 'not in progress' folders to print.  Details:  {1}{2}",
                                                                   printFolders.Count().ToString(CultureInfo.InvariantCulture),
                                                                   Environment.NewLine,
                                                                   string.Join(" ", printFolders.Select(pf => (pf + Environment.NewLine)))));

                        printFolders.ForEach(pf => Directory.Move(pf, pf + "-Processing"));
                        printFolders = printFolders.Select(pf => pf + "-Processing").ToList();
                    }

                    foreach (var printFolder in printFolders)
                    {
                        PrintLoggingSource.Log.Debug(string.Format("Beginning processing of {0}.", printFolder));
                        var closurePrintFolder = printFolder;

                        var printImages = Directory.GetFiles(closurePrintFolder).Where(f => !f.EndsWith("Thumbs.db")).ToList();
                        if (!printImages.Any()) //if there are no images, log that fact and delete the folder
                        {
                            PrintLoggingSource.Log.Warn(string.Format("No files found to delete in {0}.  Deleting folder.", closurePrintFolder));
                            LoggingSource.Log.Warn(string.Format("No files found to delete in {0}.  Deleting folder.", closurePrintFolder));

                            _DeleteFolder(closurePrintFolder);
                            continue;
                        }

                        var totalPageCount = printImages.Count;
                        var currentPageIndex = 0;

                        PrintLoggingSource.Log.Debug(string.Format("Will attempt to print {0} pages.", totalPageCount.ToString(CultureInfo.InvariantCulture)));

                        using (var pd = new PrintDocument()) //using stmt is new
                        { 
                            pd.DefaultPageSettings.PrinterSettings.PrinterName = SomethingApp.IseConfig.PrinterName;
                            pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                            pd.DefaultPageSettings.Color = false;

                            pd.PrintController = new StandardPrintController(); //new

                            PrintLoggingSource.Log.Debug(pd.PrintController.GetType().ToString());

                            pd.BeginPrint += (sender, args) => PrintLoggingSource.Log.Debug(string.Format("BeginPrint fired.  Printing from folder: {0}", closurePrintFolder));
                            pd.EndPrint += (sender, args) => PrintLoggingSource.Log.Debug(string.Format("EndPrint fired.  Printed from folder: {0}", closurePrintFolder));
                            pd.Disposed += (sender, args) => PrintLoggingSource.Log.Debug(string.Format("Disposed fired.  Printed from folder: {0}", closurePrintFolder));
                            pd.QueryPageSettings += (sender, args) => PrintLoggingSource.Log.Debug(string.Format("QueryPageSettings fired.  Are print settings valid:  {0}", args.PageSettings.PrinterSettings.IsValid));

                            pd.PrintPage += (sender, args) =>
                            {
                                PrintLoggingSource.Log.Debug(string.Format("Starting to print page {0}", currentPageIndex.ToString(CultureInfo.InvariantCulture)));


                                PrintLoggingSource.Log.Debug("Using new using statement with the FileStream");
                                PrintLoggingSource.Log.Debug("FileName: " + printImages[currentPageIndex]);
                                using (var fs = new FileStream(printImages[currentPageIndex], FileMode.Open, FileAccess.ReadWrite))
                                {
                                    using (var imageToPrint = Image.FromStream(fs, true, false))
                                    {
                                        //determine our scale and then make it a little smaller b/c there's still a small margin around the page
                                        var scale = ((double)args.MarginBounds.Height / imageToPrint.Height) * .94;
                                        args.Graphics.DrawImage(imageToPrint, 0, 0,
                                            (int)Math.Floor(imageToPrint.Width * scale),
                                            (int)Math.Floor(imageToPrint.Height * scale));

                                        currentPageIndex++;
                                    }
                                }

                                if (currentPageIndex < totalPageCount)
                                {
                                    args.HasMorePages = true;
                                }
                                else
                                {
                                    args.HasMorePages = false;
                                    _DeleteFolder(closurePrintFolder);
                                }
                            };

                            if (pd.DefaultPageSettings.PrinterSettings.IsValid)
                            {
                                PrintLoggingSource.Log.Debug("Settings are valid.  Calling the print() function.");
                                LoggingSource.Log.Info("Settings are valid.  Calling the print() function.");
                                pd.Print();
                            }
                            else
                            {
                                var printerName = SomethingApp.IseConfig.PrinterName;
                                PrintLoggingSource.Log.Warn(string.Format("Printer {0} failed to print because of incorrect configuration.", printerName));
                                LoggingSource.Log.Warn(string.Format("Printer {0} failed to print because of incorrect configuration.", printerName));
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                PrintLoggingSource.Log.Error(ex);
                LoggingSource.Log.Error(ex, "Print image failed to print");
            }
            //}
        }

        private void _DeleteFolder(string folderPath)
        {
            PrintLoggingSource.Log.Debug(string.Format("Printing complete.  Deleting {0} directory.", folderPath));
            LoggingSource.Log.Info(string.Format("Printing complete.  Deleting {0} directory.", folderPath));

            var dInfo = new DirectoryInfo(folderPath);
            dInfo.Delete(true); //delete recursively
        }
    }
}

在机器重启后,此代码完美无缺,除了。机器重启后,这就是日志文件的样子:

2015-10-16 11:39:37:9026    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Found 1 'not in progress' folders to print.  Details:  
C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\197399ba-05d5-4ce9-b00a-97123ed6ff26

2015-10-16 11:39:37:9026    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Beginning processing of C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\197399ba-05d5-4ce9-b00a-97123ed6ff26-Processing.
2015-10-16 11:39:37:9026    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Will attempt to print 1 pages.
2015-10-16 11:39:37:9026    Type: Verbose   Id: 1   Host: SomeMachineName   Message: System.Drawing.Printing.StandardPrintController
2015-10-16 11:39:38:1053    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Settings are valid.  Calling the print() function.
2015-10-16 11:39:38:1365    Type: Verbose   Id: 1   Host: SomeMachineName   Message: BeginPrint fired.  Printing from folder: C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\197399ba-05d5-4ce9-b00a-97123ed6ff26-Processing

即使一次打印尝试失败,打印也能正常工作。以下是日志中成功打印作业的内容:

2015-10-16 11:56:00:2530    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Found 1 'not in progress' folders to print.  Details:  
C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\81fb90cd-31bb-4abf-a73f-f67f83865d70

2015-10-16 11:56:00:2530    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Beginning processing of C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\81fb90cd-31bb-4abf-a73f-f67f83865d70-Processing.
2015-10-16 11:56:00:2530    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Will attempt to print 1 pages.
2015-10-16 11:56:00:2530    Type: Verbose   Id: 1   Host: SomeMachineName   Message: System.Drawing.Printing.StandardPrintController
2015-10-16 11:56:00:3308    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Settings are valid.  Calling the print() function.
2015-10-16 11:56:00:3465    Type: Verbose   Id: 1   Host: SomeMachineName   Message: BeginPrint fired.  Printing from folder: C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\81fb90cd-31bb-4abf-a73f-f67f83865d70-Processing
2015-10-16 11:56:00:6746    Type: Verbose   Id: 1   Host: SomeMachineName   Message: QueryPageSettings fired.  Are print settings valid:  True
2015-10-16 11:56:01:0183    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Starting to print page 0
2015-10-16 11:56:01:0183    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Using new using statement with the FileStream
2015-10-16 11:56:01:0183    Type: Verbose   Id: 1   Host: SomeMachineName   Message: FileName: C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\81fb90cd-31bb-4abf-a73f-f67f83865d70-Processing\635690182882039735.png
2015-10-16 11:56:01:1747    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Printing complete.  Deleting C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\81fb90cd-31bb-4abf-a73f-f67f83865d70-Processing directory.
2015-10-16 11:56:01:2216    Type: Verbose   Id: 1   Host: SomeMachineName   Message: EndPrint fired.  Printed from folder: C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\81fb90cd-31bb-4abf-a73f-f67f83865d70-Processing
2015-10-16 11:56:01:2528    Type: Verbose   Id: 1   Host: SomeMachineName   Message: Disposed fired.  Printed from folder: C:\Users\UserName\Documents\Something\Apps\Print\PrintImages\81fb90cd-31bb-4abf-a73f-f67f83865d70-Processing

到目前为止,我已经尝试过了:

  • 重新启动后和打印前清除打印队列
  • 重新启动后和打印前通过PowerShell重新添加打印机端口
  • 重新启动后和打印前通过PowerShell重新添加打印机
  • 我已经使用handle.exe来确定是否存在可能存在问题的文件锁模式(还没有)。
  • 我试图关闭Thumbs.db文件的生成,以防它们在这种疯狂中发挥作用。
  • 我已经检查了Windows事件日志,看看是否有任何错误,可能是我没有看到。
  • 我查看了PrintDocumentStandardDocumentPrintController的代码,希望在那里找到明显的东西(我不是很成功)。
    • 许多其他事情徒劳地试图找出可能发生的事情。

请帮助我提出理论/想法,了解为什么打印过程可能会在重新启动后 失败,而不是其他时间。我觉得我必须错过一些明显的东西。

0 个答案:

没有答案
相关问题