在 C# WPF 中将 Word 文档转换为 XPS 文档

Converting Word Document to XPS Document in C# WPF

我正在开发一个使用 XPS 文档的应用程序。我有word文档,想把word文档全部转成XPS文档。

我有一个主要的文件夹(说明),里面(说明)还有许多其他文件夹。每个文件夹都有那么多 Word 文档。如何将所有这些 Word 文档递归地转换为 XPS 文档

目前我有将 Word 转换为 XPS 的功能

public static string convertWordToXps(string path, string wordDocName)
    {
        Word.Application wordApp = new Word.Application();
        wordApp.Documents.Open(string.Concat(path, "\", wordDocName), ConfirmConversions: false, ReadOnly: true);
        string xpsFile = string.Concat(path, "\", Path.GetFileNameWithoutExtension(wordDocName), ".xps");

        try
        {
            //wordApp.ActiveDocument.ExportAsFixedFormat(xpsFileName, WdExportFormat.wdExportFormatXPS, false, WdExportOptimizeFor.wdExportOptimizeForOnScreen, WdExportRange.wdExportAllDocument, 1, 1, WdExportItem.wdExportDocumentContent, false, true, WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, true, false, nullObject);
            wordApp.ActiveDocument.SaveAs2(xpsFile, FileFormat: Word.WdSaveFormat.wdFormatXPS);
            return xpsFile;
        }
        catch (Exception e)
        {
            MessageBox.Show(e.getDetailedErrorMessage());
        }
        finally
        {
            wordApp.Quit(SaveChanges: false, OriginalFormat: Type.Missing, RouteDocument: Type.Missing);
        }
        return null;
    }

我写了一个静态方法来满足您的需求。

static void SearchDocuments(string directoryPath)
    {
        try
        {
            foreach (string fullName in System.IO.Directory.GetFiles(directoryPath,"*.docx")) // if your word documents come from an older version of word, they might have .doc extenstion
            {
                convertWordToXps(System.IO.Path.GetDirectoryName(fullFileName), System.IO.Path.GetFileNameWithoutExtension(fullFileName));
            }
            foreach (string nestedDirectory in System.IO.Directory.GetDirectories(directoryPath))
            {
                SearchDocuments(nestedDirectory);
            }
        }
        catch (System.Exception error)
        {
            //Do whatever u want on exception
        }
    }

顺便说一句。想想你是否有理由使用静态函数。