显示一个打印对话框以在目录中打印多个文件或将所有文件发送到打印机

时间:2016-11-18 23:01:05

标签: c# .net winforms printing dialog

我正在使用WinForms。我希望能够在特定目录中打印所有TIF图像。我的代码的问题是当我尝试打印所有tif图像时,打开每个tif图像的打印对话框。例如,如果我在目标中有10个tif图像,则每个tif图像的打印对话框将打开10次。

目标:来自这2个选项

  • 有一个对话框,如图2 ,显示所有tif 要打印的图像。
  • 将目录中的所有文件发送到默认打印机而不使用打印对话框 弹出。

    List<string> elements = new List<string>();
    private int ElementCounter;
    private void btn_Print_Click(object sender, EventArgs e)
    {
        DirectoryInfo directory = new DirectoryInfo(@"C:\image\Shared_Directory\Printing_Folder\");
        FileInfo[] Files = directory.GetFiles("*.tif"); //Getting Tif files
    
    
        foreach (FileInfo file in Files)
        {               
    
            elements.Add(file.Name);
            string FileToPrint = directory + elements[ElementCounter];
    
            //Print
            ProcessStartInfo info = new ProcessStartInfo(FileToPrint);
            info.Verb = "Print";
            info.CreateNoWindow = true;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            Process.Start(info);
    
            ElementCounter++;
        }
    }
    

    问题 enter image description here

图2:此打印对话框包含要打印的所有tif图像。 我在这里使用Windows Explore来展示示例。 enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将PrintDocument对象与PrintPreviewDialog一起使用:

private PrintDocument printDoc;
private PrintPreviewDialog printPreview;
List<string> elements = new List<string>();
private int ElementCounter;
private int page;

printDoc.BeginPrint += PrintDoc_BeginPrint;
printDoc.PrintPage += PrintDoc_PrintPage;

private void PrintDoc_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
    page = 0;
}

private void PrintDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    e.Graphics.DrawImage(Image.FromFile(elements[page]), e.MarginBounds);
    page++;
    e.HasMorePages = page < elements.Count;
}

private void btn_Print_Click(object sender, EventArgs e)
{
    DirectoryInfo directory = new DirectoryInfo(@"C:\image\Shared_Directory\Printing_Folder\");
    FileInfo[] Files = directory.GetFiles("*.tif"); //Getting Tif files


    foreach (FileInfo file in Files)
    {              
        elements.Add(file.FullName);
        ElementCounter++;
    }

    printPreview.Document = printDoc;
    printPreview.Show();
}