簡體   English   中英

在 C# WPF 中將 Word 文檔轉換為 XPS 文檔

[英]Converting Word Document to XPS Document in C# WPF

我正在開發一個使用 XPS 文檔的應用程序。 我有 word 文檔,我想將所有 word 文檔轉換為 XPS 文檔。

我有一個主文件夾(說明),里面(說明)還有許多其他文件夾。 每個文件夾都有很多 Word 文檔。 如何遞歸地將所有這些 Word 文檔轉換為 XPS 文檔

目前我有這個 Function 正在將 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 方法來滿足你的需要。

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
        }
    }

順便提一句。 考慮一下您是否有理由使用 static 函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM