0

我的 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);
        }     

所以我的问题是......为什么会发生这种情况,我做错了什么?

4

1 回答 1

1

好吧,这里没有具体的问题,但我会告诉你我所知道的。您正在使用默认打印机的驱动程序来生成要保存到文件的输出文档。一些驱动程序输出 xps 内容,然后打印机使用这些内容将墨水/碳粉放在页面上。其他驱动程序输出 postscript、PCL、PDF 或其他一些数据格式。因此,根据默认打印机,您可以以其中任何一种格式保存数据。

为确保您实际生成 XPS 内容,您需要将“Microsoft XPS Document Writer”指定为要在p.PrinterSettings.PrinterName. 当然,如果该打印队列已被重命名或删除,这可能会失败。您可以跳过一些麻烦PrinterSettings.InstalledPrinters来尝试确定哪个队列是 XPS 文档编写器,但同样,如果打印机已被移除,这将失败。更强大的解决方案是直接使用 生成 XPS 内容XpsDocumentWriter,但这需要进行一些实质性更改。

于 2013-10-02T13:26:16.293 回答