taji01 taji01 - 13 days ago 6
C# Question

Display one print dialog box to print multiple files in directory or send all files to printer

I'm using

WinForms
. I want to be able to print all TIF images in a particular directory. The problem with my code is that when i try to print all the tif images, the print dialog box opens up for each tif images. For example, If I have 10 tif images in the direcotry, the print dialog box will open up 10 times for each tif image.

Goal: From these 2 options


  • Have one dialog box like figure 2 that displays all tif
    images to be printed.

  • Send all files in the directory to default printer without the print dialogbox
    poping up.

    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++;
    }
    }


    Issue
    enter image description here



Figure 2: This print dialog box contains all the tif images to be printed. I'm using Windows Explore here to show an example.
enter image description here

Answer

You could use a PrintDocument object along with a 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();
}
Comments