也可以使用打印队列打印到 XPS 文档编写器,但它始终会显示文件对话框。
请参阅下面的其他替代方法来转换和打印到 XPS 文件。
以编程方式将文件转换为 XPS
这并不像您希望许多用户尝试过的那么简单,并且有许多不同的方法可以完成这一切,但都不是最好的。
将文档转换为 XPS 的一种方法(最简单的方法)是使用 WORD 2007+ API 来完成。
请参阅下面来自此 MSDN 论坛 question 的片段
要使用 Word 2007 以编程方式将 docx 转换为 xps,请参阅
Document.ExportAsFixedFormat 在 Word 对象模型参考中
(http://msdn2.microsoft.com/en-us/library/Bb256835.aspx)。然而,
因为这是一个服务器端方案,您应该注意 KB 257757
Office 服务器端自动化的注意事项(请参阅
http://support.microsoft.com/kb/257757)。
将图像打印到 XPS
您可以使用以下代码轻松地将图像打印到 XPS 文件。
下面的代码是 WPF 示例,您传递给 write 方法的图像需要包装在画布中,请参阅此帖子以获取示例:http://denisvuyka.wordpress.com/2007/12/03/wpf-diagramming-saving-you-canvas-to-image-xps-document-or-raw-xaml/
XpsDocument xpsd = new XpsDocument("C:\\YourXPSFileName.xps", FileAccess.ReadWrite);
System.Windows.Xps.XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
xw.Write(YourImageYouWishToWrite);
请参阅下面的扩展示例:
public void Export(Uri path, Canvas surface)
{
if (path == null) return;
// Save current canvas transorm
Transform transform = surface.LayoutTransform;
// Temporarily reset the layout transform before saving
surface.LayoutTransform = null;
// Get the size of the canvas
Size size = new Size(surface.Width, surface.Height);
// Measure and arrange elements
surface.Measure(size);
surface.Arrange(new Rect(size));
// Open new package
Package package = Package.Open(path.LocalPath, FileMode.Create);
// Create new xps document based on the package opened
XpsDocument doc = new XpsDocument(package);
// Create an instance of XpsDocumentWriter for the document
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
// Write the canvas (as Visual) to the document
writer.Write(surface);
// Close document
doc.Close();
// Close package
package.Close();
// Restore previously saved layout
surface.LayoutTransform = transform;
}
有第三方工具可让您将 PDF 和其他文件格式打印到 XPS。
打印 XPS 文件
可以以编程方式打印 XPS 文档 对于此解决方案,您至少需要 .Net 4。
下面的示例使用 WPF 中的打印对话框以及 System.Windows.Xps 和 System.Printing 中的一些类。
下面的代码会将 Xps 文件打印到系统上的默认打印机,但是如果您想打印到不同的打印机甚至打印到打印服务器,您需要更改打印对话框中的 PrintQueue 对象。
使用 System.Printing 命名空间非常简单。
请参见下面的示例。
请记住,因为它使用的是 WPF 对话框,所以它需要在 STATThread 模型上运行。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Xps.Packaging;
namespace ConsoleApplication
{
class Program
{
[STAThread]
static void Main(string[] args)
{
PrintDialog dlg = new PrintDialog();
XpsDocument xpsDoc = new XpsDocument(@"C:\DATA\personal\go\test.xps", System.IO.FileAccess.Read);
dlg.PrintDocument(xpsDoc.GetFixedDocumentSequence().DocumentPaginator, "Document title");
}
}
}
请参阅下面的一些有用链接。
- Xps Document documentation
- Print Dialog from WPF documentation
- System.Printing namespace documentation
希望这有助于并满足您的需求