XPS 是XML Paper Specification(XML文件规格书)的简称,是一种电子文件格式,它是微软公司开发的一种文档保存与查看的规范。.NET平台下,对操作XPS文件格式,提供了支持。另外,在WPF中,可以使用DocumentViewer来浏览XPS文件。这时只需把word转换为XPS,再用DocumentViewer来显示,问题就得到了很好的解决。下面是word转换为xps的方法,需要引用Microsoft.Office.Interop.Word组件。
private XpsDocument ConvertWordToXPS(string wordDocName)
{
FileInfo fi=new FileInfo(wordDocName);
XpsDocument result = null;
string xpsDocName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), fi.Name);
xpsDocName = xpsDocName.Replace(".docx", ".xps").Replace(".doc", ".xps");
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
try
{
if (!File.Exists(xpsDocName))
{
wordApplication.Documents.Add(wordDocName);
Document doc = wordApplication.ActiveDocument;
doc.ExportAsFixedFormat(xpsDocName, WdExportFormat.wdExportFormatXPS, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateHeadingBookmarks, true, true, false, Type.Missing);
result = new XpsDocument(xpsDocName, System.IO.FileAccess.Read);
}
if (File.Exists(xpsDocName))
{
result = new XpsDocument(xpsDocName, FileAccess.Read);
}
}
catch (Exception ex)
{
string error = ex.Message;
wordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);
}
wordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);
return result;
}
使用:
docViewer.Document = ConvertWordToXPS(filePath).GetFixedDocumentSequence();
docViewer.FitToWidth();
这篇文档对您是否有帮助?