Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically print to a virtual printer (XPS)

I'm going to display a portion of my C# WinForms app using PrintDocument, it's almost done, but there is a problem with my printers. I use following codes to capture an image of my form and then print this image, finally I use a PrintPreviewDialog to display a print preview:

PrintDocument doc = new PrintDocument();
doc.PrintPage += doc_PrintPage;
doc.Print();
printPreviewDialog1.Document = doc;
printPreviewDialog1.ShowDialog();

and this is doc_PrintPage function:

Bitmap bmp = new Bitmap(tabControl1.Width, tabControl1.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
tabControl1.DrawToBitmap(bmp, new Rectangle(0, 0, tabControl1.Width, tabControl1.Height));
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
e.Graphics.DrawImage((Image)bmp, 0, 0);

When doc.print() function is called, Microsoft OneNote program is opened and displays my printed form, and also PrintPreviewDialog control opens a new form which contains my preview.

I'm going to have a silent print, so that no printer program (like OneNote which is set as my default printer) or no physical printer is opened (I think if my user has a physical printer attached, the page will be actually printed! which exactly is not what I want). I just want to display a print preview without any printing, is there any way I can print to an XPS (virtual printer file?) or any other way that no actual printing is performed?

like image 688
Ali_dotNet Avatar asked May 05 '13 16:05

Ali_dotNet


1 Answers

I cannot add comments, therefore an answer. The suggestion of Peter Ritchie is correct, if you want to be sure, that the printout will not end in the (virtual) printer.

I've checked the PrintPreviewDialog and this is what I got working:

PrintDocument doc = new PrintDocument();
doc.PrinterSettings.PrinterName = this.m_printingParameters.SelectedPrinterName;
doc.PrinterSettings.PrintFileName = Path.Combine(Path.GetTempPath(), "Temporary_result.xps");
doc.PrinterSettings.PrintToFile = true;
doc.PrintPage += doc_PrintPage;

PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
printPreviewDialog1.Document = doc;
printPreviewDialog1.ShowDialog();

If the user clicks on the print icon, the result will be printed to file placed in temporary folder. Just to be sure you can delete the file afterwards.

Still, if you want to create a print preview dialog without print button, check this topic Disabling "print" button in .net print preview dialog

Is it what you were looking for?

like image 195
Mike Avatar answered Nov 10 '22 09:11

Mike