我的 C# 应用程序将一些页面打印到 xps 文件,但是我发现如果默认打印机是网络打印机,则创建的 xps 文件无效“XPS 查看器无法打开此文档”。
这让我很困惑,因为我什至没有写入网络打印机..而是写入文件。
如果我没有将默认打印机设置为联网打印机(默认打印机是“发送到 OneNote”或“Microsoft XPS 文档编写器”),那么下面的代码在执行时会正确创建一个包含 2 页的 XPS 文件:
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);
}
所以我的问题是......为什么会发生这种情况,我做错了什么?