Reputation: 3096
My C# application prints some pages to a xps file, however i have discovered that if the default printer is a networked printer then the created xps file is invalid "The XPS viewer cannot open this document".
This confuses me since i'm not even writing to a networked printer.. but to a file.
If i don't have the default printer set to a networked printer (default printer is "send to OneNote" or "Microsoft XPS Document Writer"), then the bellow code correctly creates a XPS file with 2 pages when executed:
pageCounter = 0;
PrintDocument p = new PrintDocument();
p.PrintPage += delegate(object sender1, PrintPageEventArgs e1)
{
// 8.5 x 11 paper:
float x0 = 25;
float xEnd = 850 - x0;
float y0 = 25;
float yEnd = 1100 * 2 - y0; // bottom of 2ed page
Font TitleFont = new Font("Times New Roman", 30);
if (pageCounter == 0) // for the first page
{
e1.Graphics.DrawString("My Title", TitleFont, new SolidBrush(Color.Black), new RectangleF(300, 15, xEnd, yEnd));
e1.HasMorePages = true; // more pages
pageCounter++;// next page counter
}
else // the second page
{
e1.Graphics.DrawString("Page 2", TitleFont, new SolidBrush(Color.Black), new RectangleF(300, 15, xEnd, yEnd));
}
};
// now try to print
try
{
p.PrinterSettings.PrintFileName = fileName; // the file name set earlier
p.PrinterSettings.PrintToFile = true; // print to a file (i thought this would ignore the default printer)
p.Print();
}
catch (Exception ex)
{
// for the Bug I have described, this Exception doesn't happen.
// it creates an XPS file, but the file is invalid in the cases mentioned
MessageBox.Show("Error", "Printing Error", MessageBoxButton.OK);
}
so my question is... why does this happen, what am i doing wrong?
Upvotes: 0
Views: 1932
Reputation: 3065
Well, there's no specific question here, but I'll tell you what I know. You are using the default printer's driver to generate the output document that is being saved to a file. Some drivers output xps content that is then consumed by the printer to put ink/toner on the page. Other drivers output postscript, PCL, PDF, or some other data format. So, depending on the default printer, you could be saving data in any one of these formats.
To ensure that you actually produce XPS content, you would need to specify the "Microsoft XPS Document Writer" as the printer to use in p.PrinterSettings.PrinterName
. Of course, this could fail if that print queue has been renamed or removed. You could jump through some hoops with PrinterSettings.InstalledPrinters
to try and determine which queue is the XPS Document Writer, but again, this will fail if the printer has been removed. A more robust solution would be to generate the XPS content directly with an XpsDocumentWriter
, however that would require some substantial changes.
Upvotes: 1