I am currently working on an application which creates many WPF controls, batches them and then sends them to a printer.
The problem I am having is that the application waits for the previous batch to finish before creating the next batch. This means that the printer is then waiting for the second batch rather than it being ready when it finishes printing the first batch.
Is there any way I can send a fixed document to print async??
Here is what I have so far...
void PrintInBatch(IList<object> objsToPrint, int batchSize)
{
int printed = 0;
while (printed < objsToPrint.Count())
{
IList<object> batchToPrint = objsToPrint.Skip(printed).Take(batchSize);
this.Print(batchToPrint);
printed += batchSize;
}
}
void Print(IList<object> objsToPrint)
{
const double width = 5.8*96;
const double height = 8.3*96;
var pageSize = new Size(width, height); // A5 page, at 96 dpi
var document = new FixedDocument();
document.DocumentPaginator.PageSize = pageSize;
int iii = 0;
//Add packslips to document
foreach (object objToPrint in objsToPrint)
{
PrintControl printControl = new PrintControl();
printControl.SetDetails(objToPrint);
var fixedPage = new FixedPage();
fixedPage.Width = pageSize.Width;
fixedPage.Height = pageSize.Height;
fixedPage.Children.Add(printControl);
fixedPage.Measure(pageSize);
fixedPage.Arrange(new Rect(new Point(), pageSize));
fixedPage.UpdateLayout();
var pageContent = new PageContent();
((IAddChild) pageContent).AddChild(fixedPage);
document.Pages.Add(pageContent);
}
PrintQueue queue = new LocalPrintServer().GetPrintQueue(printerName);
dlg.PrintQueue = queue;
PageMediaSize pageMedia = new PageMediaSize(PageMediaSizeName.ISOA5);
dlg.PrintTicket.PageMediaSize = pageMedia;
dlg.PrintTicket.Duplexing = Duplexing.OneSided;
dlg.PrintDocument(document.DocumentPaginator, "Packslips"); //Program waits here until print finished
}
I have tried running dlg.PrintDocument() method on a separate thread but this causes an error.
Any ideas??
Thanks
UPDATE
I have tried threading the PrintInBatch(); and this does work however it means that every batch is created at the same time, which is a massive resource drain.
I did it like this:
void PrintInBatch(IList<object> objsToPrint, int batchSize)
{
int printed = 0;
while (printed < objsToPrint.Count())
{
IList<object> batchToPrint = objsToPrint.Skip(printed).Take(batchSize);
Thread thread = new Thread(() => this.Print(batchToPrint));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
printed += batchSize;
}
}